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

Android 通知列實作全解析:常駐通知與自訂版面

編輯:關於 Android 程式設計

改 Twigee 原始碼時遇到一個需求:讓通知常駐在通知列裡。原本的寫法只會出現在「通知」分組,想把它移到「正在執行」那一組卻摸不著頭緒,翻過官方文件後才找到答案——在 Notification 的 flags 加上 FLAG_ONGOING_EVENT 即可。順便把整個 Notification 的使用方式整理成這篇筆記。

一、使用系統預建的 Notification

最傳統的做法是先向系統取得 NotificationManager,填好圖示、提示文字與時間等屬性,再把 Intent 包裝成 PendingIntent 綁上去。

// 取得 NotificationManager 的參考
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

// 定義 Notification 的各種屬性
int icon = R.drawable.icon;              // 通知圖示
CharSequence tickerText = "Hello";       // 狀態列顯示的提示文字
long when = System.currentTimeMillis();  // 通知產生的時間,會顯示在通知裡

// 用上面的屬性初始化 Notification
Notification notification = new Notification(icon, tickerText, when);

/*
 * 加入提示音
 * notification.defaults |= Notification.DEFAULT_SOUND;
 * 或者使用自訂音檔:
 * notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");
 * notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");
 * 若希望聲音持續播放直到使用者回應,可在 flags 加上 FLAG_INSISTENT
 * 注意:若 defaults 已包含 DEFAULT_SOUND,會覆蓋 sound 欄位的設定
 */

/*
 * 加入震動
 * notification.defaults |= Notification.DEFAULT_VIBRATE;
 * 也可以自訂震動節奏:
 * long[] vibrate = {0, 100, 200, 300}; // 立即開始、震 100ms、停 200ms、再震 300ms
 * notification.vibrate = vibrate;
 * long 陣列的長度可以自訂
 * 若 defaults 已包含 DEFAULT_VIBRATE,會覆蓋 vibrate 欄位的設定
 */

/*
 * 加入 LED 燈提醒
 * notification.defaults |= Notification.DEFAULT_LIGHTS;
 * 或者自訂閃爍模式:
 * notification.ledARGB = 0xff00ff00;
 * notification.ledOnMS = 300;   // 亮燈時間
 * notification.ledOffMS = 1000; // 熄燈時間
 * notification.flags |= Notification.FLAG_SHOW_LIGHTS;
 */

/*
 * 其他常用的旗標
 * notification.flags |= FLAG_AUTO_CANCEL;     // 點擊通知後自動清除
 * notification.flags |= FLAG_INSISTENT;       // 持續發出聲音直到使用者回應
 * notification.flags |= FLAG_ONGOING_EVENT;   // 放入「正在執行」分組
 * notification.flags |= FLAG_NO_CLEAR;        // 清除全部通知時仍保留此通知
 *                                             // 常與 FLAG_ONGOING_EVENT 搭配使用
 * notification.number = 1;                    // 疊在狀態列圖示右上角的事件數量,需從 1 起算
 * notification.iconLevel = 0;                 // 多狀態圖示時用來切換等級
 */

// 設定點擊通知後要處理的事情
Context context = getApplicationContext();
CharSequence contentTitle = "My Notification";  // 通知欄標題
CharSequence contentText = "Hello World!";       // 通知欄內容
Intent notificationIntent = new Intent(this, Main.class); // 點擊後要跳轉的 Activity
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

// 發送通知
mNotificationManager.notify(0, notification);

想更新一則既有通知時,只要重新設定好 notification,再次呼叫 setLatestEventInfo() 然後 notify() 一次即可;第二個參數的 id 必須與先前相同,系統才會視為同一則通知並原地更新。

二、使用自訂版面

系統預建的樣式不夠用時,可以改用 RemoteViews 完全自刻通知內容。流程是:先定義一個版面 XML,用 RemoteViews 把它載入並填入資料,丟給 contentView;再準備一個 PendingIntent 給 contentIntent。注意使用自訂版面時不需要呼叫 setLatestEventInfo()。

1. 建立自訂版面 view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_marginRight="10dp" />
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:textColor="#000" />
</LinearLayout>

2. 在程式碼中透過 RemoteViews 設定內容

RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.view);
contentView.setImageViewResource(R.id.image, R.drawable.icon);
contentView.setTextViewText(R.id.text, "Hello, this message is in a custom expanded view");
notification.contentView = contentView;

3. 為 contentIntent 指定 PendingIntent

Intent notificationIntent = new Intent(this, Main.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.contentIntent = contentIntent;

4. 發送通知

mNotificationManager.notify(2, notification);

完整範例:

// 取得 NotificationManager 的參考
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

int icon = R.drawable.icon;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();

Notification notification = new Notification(icon, tickerText, when);

RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.view);
contentView.setImageViewResource(R.id.image, R.drawable.iconempty);
contentView.setTextViewText(R.id.text, "Hello, this is JC");
notification.contentView = contentView;

Intent notificationIntent = new Intent(this, Main.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.contentIntent = contentIntent;

// 發送通知
mNotificationManager.notify(0, notification);

三、版本演進提醒

上面這套以 new Notification(icon, tickerText, when) 搭配 setLatestEventInfo() 的寫法,在 API 11 之後已被標記為不建議使用,API 23 起更是直接移除。目前的正確做法是用 Notification.Builder 串起各項設定,最後呼叫 build() 取得 Notification 物件;自訂版面則改用 RemoteViews 搭配 setCustomContentView()。此外從 Android 8.0 開始,所有通知都必須綁定一個 notification channel,否則根本不會顯示。理解這裡談到的旗標與 RemoteViews 觀念後,再對照新版 API 調整即可無痛遷移。

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