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

Android 如何累計未讀通知數量

編輯:關於 Android 程式設計

問題描述:我在 Android 應用程式中加入了通知功能,希望每收到一則通知,未讀數量就累加。原本使用 notification.number 的寫法如下:

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, "A new notification", System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.number += 1;
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);
notification.setLatestEventInfo(this, "This is the title", "This is the text", activity);
notificationManager.notify(0, notification);

但不管收到多少通知,未讀數量一直顯示為 1,並沒有累加。

解決方案

問題出在你每次都重新建立了一個新的 Notification 物件,導致 number 每次都被重置。正確做法是把 Notification 宣告為成員變數,只建立一次,之後檢查它是否存在並累加 number:

public class main extends Activity {
  Notification notification = null;
  // ...
  if (this.notification == null) {
    this.notification = new Notification(R.drawable.icon, "A new notification", System.currentTimeMillis());
  }
  this.notification.flags |= Notification.FLAG_AUTO_CANCEL;
  this.notification.number += 1;
}

如此一來,number 便能在同一個 Notification 物件上持續累加,正確顯示未讀通知的數量。

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