通知是應用程式在不在前景時,向使用者傳遞訊息的標準管道。相關操作其實不複雜:取得系統服務 NotificationManager,建立 Notification 物件並設定屬性,最後呼叫 notify 發出即可。
第一步,取得管理器:
String service = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(service);
第二步,建立 Notification 並設定圖示、提示文字與時間:
Notification notification = new Notification(); int icon = R.drawable.happy; notification.icon = icon; notification.tickerText = "測試 Notification"; notification.when = System.currentTimeMillis();
第三步,用 PendingIntent 決定點擊後要前往的畫面,再呼叫 setLatestEventInfo 掛上標題與內容。
第四步,發出通知。notify 的第一個參數是通知 ID,同 ID 會覆蓋前一則,取消時則呼叫 cancel(ID)。
以下組合示範了典型的通知鏈路:MainActivity 按鈕發出自訂 action 的廣播,MyReceiver 收到後啟動 SecondActivity,SecondActivity 真正把通知推上狀態列。
public class MyReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Intent i = new Intent();
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setClass(context, SecondActivity.class);
context.startActivity(i);
}
}
String service = NOTIFICATION_SERVICE; mNotification = (NotificationManager) getSystemService(service); notification = new Notification(); notification.icon = android.R.drawable.stat_notify_chat; notification.tickerText = "Test Notification"; notification.when = System.currentTimeMillis(); Intent intent = new Intent(this, MainActivity.class); PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0); notification.setLatestEventInfo(this, "消息", "Hello Android", pi); mNotification.notify(ID, notification);
setLatestEventInfo 在 API 23 之後已被移除,新專案請改用 Notification.Builder 串接式設定; targeting Android 8.0 以上時,還必須先建立 NotificationChannel 並指定 importance,否則通知不會顯示。PendingIntent 也需明確標示 FLAG_IMMUTABLE 或 FLAG_MUTABLE,這是近年 Android 版本強制要求的。若通知要能被使用者隨時關閉,就不要加上 FLAG_ONGOING_EVENT。