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

Android Notification 通知欄訊息完整指南:建立、更新與取消

編輯:關於 Android 程式設計

通知(Notification)是 App 在「不搶走使用者焦點、不打斷當前操作」的前提下,向使用者傳遞訊息的機制。它幾乎總是與 NotificationManager 搭配使用:前者描述「長什麼樣子」,後者負責「把它推出去」。

一、建立通知的基本四步

1. 取得 NotificationManager

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

2. 建立 Notification 物件

Notification notification = new Notification();
notification.icon = R.drawable.notification_icon;

也可以一次帶入三個參數,語意更清楚:

int icon = R.drawable.notification_icon;          // 通知圖示
CharSequence tickerText = "Hello";                // 狀態欄的提示文字
long when = System.currentTimeMillis();           // 通知產生時間
Notification notification = new Notification(icon, tickerText, when);

3. 設定各項屬性

Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
CharSequence contentText = "Hello World!";
Intent notificationIntent = new Intent(this, MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

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

接著依需求加上提示音、震動與呼吸燈:

// 提示音:使用系統預設或自訂音效
notification.defaults |= Notification.DEFAULT_SOUND;
notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");

// 震動:陣列第一個值是靜默時間,其後為「震動、靜默」交替
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.vibrate = new long[]{0, 100, 200, 300};

// LED 呼吸燈
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.ledARGB = 0xff00ff00;
notification.ledOnMS = 300;
notification.ledOffMS = 1000;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;

4. 發送通知

private static final int ID_NOTIFICATION = 1;
mNotificationManager.notify(ID_NOTIFICATION, notification);

若希望使用者手動清除前通知都不消失,加上 notification.flags = Notification.FLAG_NO_CLEAR; 即可。

二、更新通知

更新非常直覺:重新設定好屬性後,用相同的 ID 再呼叫一次 notify()。無論你帶入的是同一個物件還是全新的物件,系統都會以 ID 為鍵去替換狀態列圖示與展開後的詳細內容。這個特性很適合做「下載進度 30% → 60% → 100%」的即時更新。

三、取消通知

notificationManager.cancel(notificationRef);

取消後,狀態列圖示會被移除,展開的詳細資訊也會一併清除。共有四種取消途徑:呼叫 cancel(id)、呼叫 cancelAll()、使用者手動滑掉,或加上 Notification.FLAG_AUTO_CANCEL 讓點擊後自動消失。

四、現代版本的寫法提醒

上面這套以 setLatestEventInfo() 為核心的寫法,在 API 23 之後已被移除。Android 8.0(API 26)起更強制要求建立通知 channel,否則通知根本不會顯示。目前的標準寫法是改用 NotificationCompat.Builder:

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setAutoCancel(true)
        .setContentIntent(contentIntent);
NotificationManagerCompat.from(this).notify(ID_NOTIFICATION, builder.build());

同時別忘了在 AndroidManifest.xml 宣告 android.permission.POST_NOTIFICATIONS,並在 Android 13 以上執行期向使用者詢問通知權限。

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