每次收到通知創建新 Notification 對象,導致 notification.number 始終為 1,無法累計未讀數量。
new Notification() 每次創建實例,number 字段重置為 0 再 +1。需復用同一 Notification 實例或手動維護計數。
public class MainActivity extends Activity {
private static Notification notification; // 靜態保持單例
private static int unreadCount = 0;
private NotificationManager nm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
private void showNotification() {
if (notification == null) {
notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("新消息")
.setAutoCancel(true)
.build();
}
unreadCount++;
notification.number = unreadCount; // 累加
nm.notify(NOTIFY_ID, notification);
}
}
private void updateNotification() {
SharedPreferences sp = getSharedPreferences("notify", MODE_PRIVATE);
int count = sp.getInt("unread", 0) + 1;
sp.edit().putInt("unread", count).apply();
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("新消息 (" + count + ")")
.setNumber(count) // 設置 number 字段
.setAutoCancel(true);
nm.notify(NOTIFY_ID, builder.build());
}
Android O 引入 Channel,可通過 NotificationChannel.setShowBadge(true) 顯示角標,但數字需 Launcher 支持。應用層面仍需自行維護 Notification.number。
Notification.number 僅在同一 notify(id, notification) ID 下累加有效,不同 ID 互不影響。NotificationCompat.Builder 替代棄用的 new Notification()。NotificationChannel 才能顯示通知。notification.number = 0; nm.notify(id, notification); 或 nm.cancel(id)。new Notification(),改用 Builder 模式復用或重建並設置正確 number。ContentProvider 或 SharedPreferences(MULTI_PROCESS) 同步計數。number 僅作數據攜帶。正確維護 Notification 實例與計數邏輯,讓未讀數字準確疊加,提升用戶感知體驗。