Android:如何修复通知的递增 setNumber()?

Android: how to fix incrementing setNumber() for a Notification?

我使用从 BroadcastReceiver 启动的 JobIntentService 向用户发送截止日期临近的通知。当另一个截止日期的下一个通知临近时,我只想更新现有通知并将 setNumber() 指示器增加 +1。第一个 Notification 将 "totalMesssages" 变量正确递增 +1,并且 setNumber() 在 Notification 下拉对话框中显示“1”。下一个通知正确触发,但 setNumber() 不会增加 +1 到“2”。它保持在“1”。

我在这里错过了什么?

public class AlarmService extends JobIntentService {

    static final int JOB_ID = 9999;
    private int totalMessages = 0;

    static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, AlarmService.class, JOB_ID, work);
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent) {

    sendNotification();
    }

    private void sendNotification() {

        int notifyID = 1;

        NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);

        if (notificationManager != null) {
         notificationManager.createNotificationChannel(notificationChannel);
        }
    }

    NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
        .setDefaults(Notification.DEFAULT_ALL)
        .setSmallIcon(R.drawable.ic_announcement_white_24dp)
        .setContentText("")
        .setNumber(++totalMessages);

    Intent intent = new Intent(this, MainActivity.class);        
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(contentIntent);
    mBuilder.setAutoCancel(true);;

    if (notificationManager != null) {
        notificationManager.notify(notifyID, mBuilder.build());
    }
  }
}   
private int totalMessages = 0;

每次从 BroadcastReceiver 启动 JobIntentService 时都会初始化为 0。

解决方案之一是将 totalMessage 存储在 SharedPreferences 中并在您的 AlarmService 中使用它。

SharedPreferences sp = getApplicationContext().getSharedPreferences("preferences_name", Context.MODE_PRIVATE);
int totalMessages = sp.getInt("total-messages", 0); //initialize to 0 if it doesn't exist
SharedPreferences.Editor editor = sp.edit();
editor.putInt("total-messages",++totalMessages);
editor.apply();

您可以在代码中的通知生成器之前插入它。