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

Android 通知列基礎:Notification 與 PendingIntent 怎麼搭配

編輯:關於 Android 開發

當 App 有事情要告訴使用者,又不適合打斷他手上的操作時,通知列就是最合適的管道。本文用最精簡的兩個按鈕——一個發通知、一個取消通知——把 Notification 的基本用法走一遍。

版面:兩個按鈕就夠

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" >

    <Button android:id="@+id/bt_up"
        android:onClick="openNotify"
        android:text="open" />

    <Button android:id="@+id/bt_down"
        android:layout_below="@id/bt_up"
        android:onClick="closeNotify"
        android:text="close" />
</RelativeLayout>

三個角色先講清楚

在動手之前,先把三個容易混淆的類別分清楚:

  • NotificationManager:系統服務,負責發送與管理通知。透過 getSystemService(NOTIFICATION_SERVICE) 取得。
  • Notification:通知本身,描述圖示、標題、內容與行為。
  • PendingIntent:這是最容易搞糊塗的一個,值得多說兩句。

Intent 是即時的,它隨所在的 Activity 一起消失。而 PendingIntent 可以視為對 Intent 的包裝:它裡面保存了當前 App 的 Context,因此外部程式(在這個例子裡是系統的通知列)可以「代替你的 App」執行這個 Intent——即使執行時你的 App 已經不在前景,甚至已被結束,也一樣能運作。它常與 AlarmManager、NotificationManager 一起出現,可以理解為「延遲或委外執行的 Intent」。

程式碼

public class MainActivity extends Activity {

    private NotificationManager notifyManager;
    private Notification notify;
    private Intent intent;
    private PendingIntent pendIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        notifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    // 發送通知
    public void openNotify(View v) {
        notify = new Notification(R.drawable.ic_launcher, "通知", System.currentTimeMillis());

        intent = new Intent(getApplicationContext(), MainActivity.class);
        // requestCode 用於區分不同的 PendingIntent,後兩個參數分別是 Intent 與 flags
        pendIntent = PendingIntent.getActivity(getApplicationContext(), 100, intent, 0);

        notify.setLatestEventInfo(getApplicationContext(), "通知", "通知的內容", pendIntent);
        notify.flags = Notification.FLAG_AUTO_CANCEL;
        notifyManager.notify(100, notify);
    }

    // 取消通知
    public void closeNotify(View v) {
        pendIntent.cancel();
    }
}

幾個關鍵細節

notify(id, notification) 的 id 是通知的身份。用同一個 id 發送,會更新原本那則通知而不是疊一個新的。這在實作「下載進度」這類需要持續更新的通知時非常好用。

FLAG_AUTO_CANCEL 讓通知可以點掉。加上這個旗標後,使用者點擊通知,系統會自動把它從通知列移除。

取消通知有兩種方式。除了 pendIntent.cancel(),也可以直接呼叫 notifyManager.cancel(id),後者更直接,不必保留 PendingIntent 的參考。

這份程式碼的年代提醒

必須誠實指出:Notification 的建構方式在 Android 5.0 之後出現了 Notification.Builder,Android 8.0(API 26)更強制要求指定通知管道(NotificationChannel),而 setLatestEventInfo() 早已被移除。本文的寫法適用於早期版本,理解它的用意在於釐清 PendingIntent 的角色;實際開發時請改用 Builder 模式,並記得建立通知管道,否則在較新的系統上通知根本不會顯示。

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