安排通知
有時需要在特定時間顯示通知,不幸的是,這個任務在 Android 系統上並不重要,因為沒有方法 setTime() 或類似的通知。此示例概述了使用 AlarmManager 安排通知所需的步驟:
- 新增一個聽取 Android
AlarmManager播放的Intents 的BroadcastReceiver。
這是你根據 Intent 提供的附加功能構建通知的地方:
public class NotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Build notification based on Intent
Notification notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_notification_small_icon)
.setContentTitle(intent.getStringExtra("title", ""))
.setContentText(intent.getStringExtra("text", ""))
.build();
// Show notification
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(42, notification);
}
}
-
**** 在
AndroidManifest.xml檔案中註冊BroadcastReceiver(否則接收方將不會從AlarmManager收到任何Intent):<receiver android:name=".NotificationReceiver" android:enabled="true" /> -
**** 通過將
PendingIntent傳遞給你的BroadcastReceiver並將所需的Intent附加到系統AlarmManager來安排通知。一旦給定時間到達,你的BroadcastReceiver將收到Intent並顯示通知。以下方法安排通知:public static void scheduleNotification(Context context, long time, String title, String text) { Intent intent = new Intent(context, NotificationReceiver.class); intent.putExtra("title", title); intent.putExtra("text", text); PendingIntent pending = PendingIntent.getBroadcast(context, 42, intent, PendingIntent.FLAG_UPDATE_CURRENT); // Schdedule notification AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time, pending); }請注意,上面的
42對於每個預定的通知都必須是唯一的,否則PendingIntents 會互相替換,造成不良影響! -
**** 通過重建關聯的
PendingIntent取消通知並在系統AlarmManager上取消它。以下方法取消通知:public static void cancelNotification(Context context, String title, String text) { Intent intent = new Intent(context, NotificationReceiver.class); intent.putExtra("title", title); intent.putExtra("text", text); PendingIntent pending = PendingIntent.getBroadcast(context, 42, intent, PendingIntent.FLAG_UPDATE_CURRENT); // Cancel notification AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); manager.cancel(pending); }
請注意,上面的 42 需要匹配第 3 步的數字!