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

Android 發送多個 Notification 的關鍵

編輯:關於 Android 程式設計

在 Android 中發送多個通知(Notification)時,最容易踩的坑就是——PendingIntent 的請求碼(ID)至關重要。如果每個通知的 PendingIntent 使用了相同的 ID,系統會認為它們指向同一個意圖,導致通知被相互覆蓋,無法正常分開顯示。因此,為每個通知分配唯一的 ID,是實現多通知並存的核心。

下面的示例基於 Cordova 插件場景,示範如何發送多個可區分的通知:

public void addNotification(JSONArray args, CallbackContext callbackContext) throws JSONException {
    // NOTIFICATION_ID 至關重要,這裡隨機生成一個,確保每條通知唯一
    NOTIFICATION_ID = (int) (Math.random() * 10000);
    try {
        nm = (NotificationManager) cordova.getActivity()
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Intent intent = new Intent(cx, cordova.getActivity().getClass());
        intent.putExtra("clickAction", args.getString(4));
        String clickActionParams = args.getJSONObject(5).toString();
        intent.putExtra("clickActionParams", clickActionParams);

        PendingIntent pIntent = PendingIntent.getActivity(
                cx, NOTIFICATION_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        int version = android.os.Build.VERSION.SDK_INT;
        Notification notify;
        // 版本號大於 15 採用 Notification.Builder,否則用舊方法,避免部分機型問題
        if (version > 15) {
            notify = new Notification.Builder(cx)
                    .setAutoCancel(true)                       // 點擊後自動消失
                    .setTicker(args.getString(0))              // 狀態欄提示文字
                    .setSmallIcon(R.drawable.icon)             // 通知圖標
                    .setContentTitle(args.getString(0))        // 通知標題
                    .setContentText(args.getString(1) + NOTIFICATION_ID) // 通知內容
                    .setWhen(System.currentTimeMillis())       // 通知時間
                    .setContentIntent(pIntent).build();        // 點擊後啟動的 Intent
        } else {
            notify = new Notification(R.drawable.icon, args.getString(0),
                    System.currentTimeMillis());
            notify.setLatestEventInfo(cx, args.getString(0), args.getString(1), pIntent);
        }

        // 發送通知
        nm.notify(NOTIFICATION_ID, notify);

        // 通知顯示一段時間後自動清除
        if (args.getBoolean(2)) {
            disappearTime = args.getLong(3);
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    nm.cancel(NOTIFICATION_ID);
                }
            }, disappearTime);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

這段程式碼的關鍵有兩點:其一,NOTIFICATION_ID 唯一,且 PendingIntent 使用相同的 ID 保持一致;其二,根據系統版本選擇不同的通知構建方式,兼顧了新舊機型的相容性。掌握這兩點,你就能從容地在一個應用中推送並管理多條互不干擾的通知。

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