1

我使用JobIntentService从 a 启动的BroadcastReceiver方法向用户发送通知,告知到期日期已近。当另一个到期日的下一个通知临近时,我只想更新现有的通知并将 setNumber() 指示器增加 +1。第一个通知将“totalMesssages”变量正确增加 +1,并且 setNumber() 在通知下拉对话框中显示“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());
    }
  }
}   
4

1 回答 1

2
private int totalMessages = 0;

每次JobIntentServiceBroadcastReceiver.

解决方案之一是将 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();

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

于 2018-05-14T06:51:26.097 回答