Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 狀態列通知實作:NotificationManager 與 Notification 的基本用法

編輯:關於 Android 程式設計

要在下拉式通知列顯示一則訊息,Android 的機制是「建立一個 Notification 物件,然後交給 NotificationManager 發送」。這套寫法從 Android 1.x 一路用到今天,觀念完全沒變,只是 API 換了幾輪。

基本三件事

通知可以由 Activity 或 Service 觸發,差別在於前者是使用者操作時的前台行為,後者則能在背景自行發出——這也是為什麼「下載完成」「新訊息到達」這類通知通常寫在 Service 裡。

不論哪種,都需要兩個類別:NotificationManager 負責發送與管理,Notification 負責描述內容。前者透過 getSystemService() 取得,再用 notify(id, notification) 推給系統。

// ---- 通知列 ----

// 取得 NotificationManager
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(ns);

// 通知列上摺疊狀態顯示的內容
int icon = R.drawable.icon;
CharSequence tickerText = "我的通知欄標題";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);

// 下拉展開後顯示的內容
Context context = getApplicationContext();
CharSequence contentTitle = "我的通知欄展開標題";
CharSequence contentText = "我的通知欄展開詳細內容";

Intent notificationIntent = new Intent(this, BootStartDemo.class);
PendingIntent contentIntent = PendingIntent.getActivity(
        this, 0, notificationIntent, 0);

notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

// 發送通知,id 為 1
mNotificationManager.notify(1, notification);

這段程式在說什麼

三個參數各有分工:icon 是狀態列上那張小圖;tickerText 是通知滑入時短暫滾動的文字(在較新版本上已被省略);when 是時間戳,系統會依它排序通知。

setLatestEventInfo() 則負責設定「下拉之後看到的那一塊」,包含標題、內文,以及最關鍵的 PendingIntent——使用者點了通知之後要跳去哪裡。這裡有個觀念要釐清:PendingIntent 是「一張授權書」,你把「請幫我啟動這個 Intent」的權利交給系統,由系統在未來使用者點擊時執行,因此它不需要 Activity 存活也能運作。

notify() 的第一個參數是 id。同一個 id 重複發送會更新既有通知而非新增一則,這是做「下載進度 30% → 60% → 完成」的正確做法;不同 id 則各自獨立顯示。

這份程式碼在今天不能照抄

這裡必須誠實說明:範例中的 Notification 建構式與 setLatestEventInfo() 都是 2011 年的寫法。前者在 API 11 被棄用,後者更在 API 23 被完全移除,直接編譯會失敗。

現行的標準做法有三個重點。第一,改用 NotificationCompat.Builder,好處是它會自動套用各版本的相容處理:

Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.icon)
        .setContentTitle("我的通知欄展開標題")
        .setContentText("我的通知欄展開詳細內容")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setAutoCancel(true)
        .setContentIntent(contentIntent)
        .build();

第二,從 Android 8.0(API 26)開始,所有通知都必須先建立「通知管道」(NotificationChannel)並指定重要度,否則通知根本不會顯示:

NotificationChannel channel = new NotificationChannel(
        CHANNEL_ID, "一般通知", NotificationManager.IMPORTANCE_DEFAULT);
mNotificationManager.createNotificationChannel(channel);

第三,Android 13(API 33)起發送通知需要 POST_NOTIFICATIONS 執行期權限,未經使用者同意就呼叫 notify 會被靜默丟棄。這三點合起來,才是能實際跑在手機上的版本。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved