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

Android Notification 通知實用寫法整理

編輯:關於 Android 程式設計

Notification 讓我們能在收到訊息時,於狀態列、鎖屏介面或通知面板上呈現提示,是背景服務與使用者溝通的主要管道。以下整理不同 API Level 的寫法與清除方式。

基本寫法(API 16 以後)

// 取得通知管理器
NotificationManager manager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

// 建立 PendingIntent,決定點擊後要跳去哪裡
PendingIntent pendingIntent =
        PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);

// 透過 Notification.Builder 建立通知
// 注意:Builder 是 API 11 引入,build() 則是 API 16 才加入
Notification notify = new Notification.Builder(this)
        .setSmallIcon(R.drawable.message)
        .setTicker("您有新短訊息,請注意查收!")
        .setContentTitle("Notification Title")
        .setContentText("This is the notification message")
        .setContentIntent(pendingIntent)
        .setNumber(1)
        .build();

// 點擊後自動清除通知
notify.flags |= Notification.FLAG_AUTO_CANCEL;

// 發送通知;id 不同時每次點擊都會在狀態列累積一則
manager.notify(NOTIFICATION_ID, notify);

在 API 11 ~ 15 之間,則改用已不建議使用的 getNotification() 取代 build()。

Android 5.0 之後的寫法

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

Notification.Builder builder = new Notification.Builder(this);

Intent mIntent = new Intent(Intent.ACTION_VIEW,
        Uri.parse("https://example.com"));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, mIntent, 0);

builder.setContentIntent(pendingIntent);
builder.setSmallIcon(R.drawable.message);
// 5.0 之後可以在通知中顯示大圖示
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.message));
builder.setAutoCancel(true);
builder.setContentTitle("普通通知");

manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0, builder.build());

清除通知

// 只清除指定 id 的通知
manager.cancel(NOTIFICATION_ID);

// 清除所有由本 App 發出的通知
// manager.cancelAll();

實務上的重點

  • setSmallIcon() 是必填的,缺少會導致通知無法顯示甚至直接拋出例外。
  • setAutoCancel(true) 與 flags |= FLAG_AUTO_CANCEL 效果相同,都是點擊後自動消失,兩者擇一即可。
  • notify 的 id 決定通知的唯一性:同一個 id 重複發送會更新原通知,不同 id 則會各自獨立顯示。想做未讀計數時,善用同一 id 搭配 setNumber() 即可。
  • 點擊行為一律透過 PendingIntent 處理,這是系統延遲執行的工作,並非立即啟動 Activity。
  • Android 8.0 之後還必須建立 NotificationChannel,否則通知不會顯示,這點在舊版範例中不會提到。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved