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

Android 通知(Notification)用法整理:從基本到進階

編輯:關於 Android 程式設計

用過 Android 手機的人對通知欄都不陌生。本文把通知的建立、點擊回應、取消,以及進場提示的各種細節整理成一份可查的筆記。

一、三個 API 版本的寫法差異

通知可以在 Activity、廣播接收器或 Service 中建立。實務上通常在 App 退到背景後才發通知,所以很少寫在 Activity 裡。

API Level 11 及以前(已廢棄)

 // 獲得通知管理器
NotificationManager manager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 創建通知對象,參數依次為通知圖標、ticker(通知欄上一閃而過的信息)、通知創建時間
Notification notification = new Notification(R.drawable.ic_launcher,
        "This is ticker text", System.currentTimeMillis());
// 設置通知布局,參數依次為 Context、通知標題、通知正文、PendingIntent
notification.setLatestEventInfo(this, "This is content title",
        "This is content text", null);
// 顯示通知,參數依次為唯一的 id、通知對象
manager.notify(1, notification);

API Level 12 ~ 15

 NotificationManager manager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this)
        .setAutoCancel(true)
        .setContentTitle("title")
        .setContentText("describe")
        .setSmallIcon(R.drawable.ic_launcher)
        .setWhen(System.currentTimeMillis())
        .setOngoing(true);
Notification notification = builder.getNotification();
manager.notify(1, notification);

API Level 16 及以上

 NotificationManager manager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(this)
        .setAutoCancel(true)
        .setContentTitle("title")
        .setContentText("describe")
        .setSmallIcon(R.drawable.ic_launcher)
        .setWhen(System.currentTimeMillis())
        .setOngoing(true)
        .build();
manager.notify(1, notification);

三者的差異只在 Builder 產生 Notification 的方式:new Notification(...) → getNotification() → build()。Android 8.0 之後還必須再建立 NotificationChannel,否則通知根本不會顯示,這一點稍後補充。

二、回應通知的點擊

點擊行為靠 PendingIntent 承接。它需要先包一個 Intent,再用 PendingIntent.getActivity()、getBroadcast() 或 getService() 決定點擊後要啟動 Activity、送廣播還是啟動服務。

這三個靜態方法的參數一致:Context、requestCode(一般傳 0)、Intent,以及 flag。flag 有四種可選:

  • FLAG_ONE_SHOT:只可使用一次,用過即失效
  • FLAG_NO_CREATE:若不存在對應 PendingIntent 就回傳 null,不新建
  • FLAG_CANCEL_CURRENT:若已存在則先取消,再建立新的
  • FLAG_UPDATE_CURRENT:若已存在則更新其 extras,保留原物件

建立好之後透過 setContentIntent() 掛上去:

 NotificationManager manager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(MainActivity.this, TestActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
        PendingIntent.FLAG_CANCEL_CURRENT);

Notification notification = new Notification.Builder(this)
        .setAutoCancel(true)
        .setContentTitle("title")
        .setContentText("describe")
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentIntent(pendingIntent)
        .setWhen(System.currentTimeMillis())
        .setOngoing(true)
        .build();

manager.notify(1, notification);

setAutoCancel(true) 的意義是:使用者點了通知之後自動把它從通知欄移除。若不加,通知會一直留在那裡直到你手動取消。

三、取消通知

傳入建立通知時使用的那個 id 即可:

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

若要一次清掉該 App 發出的全部通知,改用 manager.cancelAll()。

四、進階:讓通知被「聽見」和「感覺到」

1. 播放提示音

 // 音頻 Uri
Uri soundUri = Uri.fromFile(new File("/system/media/audio/ringtones"));
setSound(soundUri);

2. 手機振動

vibrate 接受一個長整型陣列,單位為毫秒,偶數索引代表靜止時長、奇數索引代表振動時長:

 // 靜止 0 秒、振動 1 秒、靜止 1 秒、振動 1 秒
long[] vibrate = {0, 1000, 1000, 1000};
setVibrate(vibrate);

需另外在 manifest 宣告權限:

 <uses-permission android:name="android.permission.VIBRATE"/>

3. 呼吸燈閃爍

涉及三個屬性:ledARGB 控制顏色、ledOnMS 控制亮起時間、ledOffMS 控制熄滅時間,透過 setLights() 一次設定:

 setLights(Color.BLUE, 1000, 1000);

這行程式碼讓 LED 以藍色每秒明滅一次。

4. 懶人做法:全部交給系統

 .setDefaults(Notification.DEFAULT_ALL)

設成預設值後,鈴聲、振動與呼吸燈的行為都跟隨使用者目前的情景模式與設定,不必自己一個個配。

要注意的是,鈴聲、振動與呼吸燈都必須在真機上才能驗證,模擬器看不出效果。

五、給新版本的補充

本文的三段寫法對應的是較早期的 API。若你在 Android 8.0 以上的裝置上發現通知完全不顯示,原因幾乎一定是少了 Channel:

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

建立通知時再用 setChannelId("my_channel") 指定即可。此外 Android 13 起發送通知需要 POST_NOTIFICATIONS 執行期權限,而 setLatestEventInfo()、setSound() 這類直接下指令的寫法也早已被 Builder 的串接式 API 取代——新專案請直接以 Builder 加 Channel 的組合為起點。

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