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

Android 通知 PendingIntent 打開 Activity 資料不更新的解決方法

編輯:關於 Android 程式設計

在使用 Notification 搭配 PendingIntent 延遲意圖開啟 Activity 來顯示通知詳情時,常會遇到一個惱人的問題:若有多則通知抵達,但它們的 Intent 內容都一樣、只有通知文字不同,那麼多次點開通知詳情 Activity 時,顯示的資料竟然都是第一次的內容,後續資料並未更新。

問題重現

以下為典型的通知彈出程式碼:

// 彈出應用的通知,在通知欄中顯示 xx 回復的簡訊結果
private void popNotification(Context context, SmsMsg smsMsg) {
    String body = smsMsg.getBody();
    String promptContent = null;
    if (null != body && body.length() > 10) {
        promptContent = body.substring(0, 10);
    } else {
        promptContent = body;
    }
    CharSequence charDateTime =
            DateFormat.format("yyyy-MM-dd kk:mm:ss", new Date(smsMsg.getTime()));

    // 取得 NotificationManager
    NotificationManager nm =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    // 建立 Notification 物件
    Notification n = new Notification(R.drawable.ic_launcher,
            "xx簡訊提醒", System.currentTimeMillis());
    n.flags = Notification.FLAG_AUTO_CANCEL;      // 點擊後自動消失
    n.defaults |= Notification.DEFAULT_SOUND;       // 抵達時播放預設音效
    n.defaults |= Notification.DEFAULT_VIBRATE;     // 抵達時預設震動

    Intent readMsgIntent = new Intent(context, SmsReadActivity.class);
    readMsgIntent.putExtra("SmsMsg", smsMsg);       // 將簡訊帶到 Activity
    readMsgIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 在服務中開啟 Activity 需加此標記

    PendingIntent pi = PendingIntent.getActivity(context, 300, readMsgIntent, 0);
    n.setLatestEventInfo(context, "xx簡訊提醒 " + charDateTime, promptContent, pi);

    nm.notify(10, n);
}

問題根源

問題就出在這一行:

PendingIntent pi = PendingIntent.getActivity(context, 300, readMsgIntent, 0);

最後一個參數(flag)設為 0 時,即使 Intent 附带的額外資料(extras)改變了,系統仍會沿用舊的 PendingIntent,導致 Activity 拿到的永遠是第一次的資料。

解決方法

將 flag 從 0 改為 PendingIntent.FLAG_UPDATE_CURRENT:

PendingIntent pi = PendingIntent.getActivity(context, 300, readMsgIntent,
        PendingIntent.FLAG_UPDATE_CURRENT); // 點擊後開啟指定的 Activity

根據官方 API 對 FLAG_UPDATE_CURRENT 的說明:

Flag for use with getActivity, getBroadcast, and getService: if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent. This can be used if you are creating intents where only the extras change, and don't care that any entities that received your previous PendingIntent will be able to launch it with your new extras even if they are not explicitly given to it.

簡單來說,當描述的 PendingIntent 已存在時,此旗標會保留它,但用新 Intent 中的額外資料取代舊資料。這正好適用於「只有 extras 變化」的通知情境,如此每次點開通知都能正確顯示對應的最新內容。

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