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

Android 新版通知 Notification.Builder 基本用法整理

編輯:關於 Android 程式設計

寫通知功能時會發現,舊書上那套 setLatestEventInfo() 已經被標記為不建議使用,照抄下來編譯還會出現警告。以下把 Notification.Builder 這套新寫法的骨架整理出來。

一、取得 NotificationManager

NotificationManager notificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

這個物件是發送與管理通知的唯一入口,記得用 Context.NOTIFICATION_SERVICE 這個常數取值,比較不容易寫錯。

二、建立 Notification 實例

這裡要依專案的 minSdk 選擇寫法。API Level 11 以前只能用 setLatestEventInfo(),以下說明 API 11 之後的做法。

1. minSdk < 16:用 getNotification() 取得物件

Notification.Builder builder = new Notification.Builder(context)
        .setAutoCancel(true)                 // 點擊通知後自動取消
        .setContentTitle("title")            // 通知標題
        .setContentText("describe")          // 通知第二行內容
        .setContentIntent(pendingIntent)     // 點擊後要送出的 PendingIntent
        .setSmallIcon(R.drawable.ic_launcher); // 通知圖示,不設定的話通知不會顯示

Notification notification = builder.getNotification();

2. minSdk >= 16:改用 build()

Notification notification = new Notification.Builder(context)
        .setAutoCancel(true)
        .setContentTitle("title")
        .setContentText("text")
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentIntent(pendingIntent)
        .build();

這兩個版本的差別只在最後一步:getNotification() 在 API 16 之後被標記為不建議使用,改用 build() 即可。

三、發送通知

notificationManager.notify(1, notification);

第一個參數是通知 id。同一個 id 重複 notify 會更新原通知而非新增一則,想更新既有通知時就沿用同一個 id。

四、Android 8.0 之後必做的兩件事

以上寫法在 Android 8.0(API 26)之後會失效——通知根本不會跳出來。原因是從這版開始,所有通知都必須屬於一個「通知渠道」(Notification Channel),而且渠道的重要程度一旦建立就無法再修改,只能由使用者在系統設定中自行調整。

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel(
            "my_channel_id", "我的通知", NotificationManager.IMPORTANCE_DEFAULT);
    notificationManager.createNotificationChannel(channel);
}

Notification notification = new Notification.Builder(context, "my_channel_id")
        .setAutoCancel(true)
        .setContentTitle("title")
        .setContentText("text")
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentIntent(pendingIntent)
        .build();

另一件事是 Android 13(API 33)起,發送通知需要 POST_NOTIFICATIONS this 執行期權限,必須先向使用者詢問並取得同意,否則 notify() 會靜默失敗。

最後提醒,setSmallIcon() 傳入的圖示會被系統渲染成單色剪影,直接丟一張彩色 PNG 進去會得到一塊白色方塊。正確做法是準備一個透明背景的白色線條圖,放在 res/drawable 底下。

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