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

标签 android android-notifications notificationmanager jobintentservice

我使用从 BroadcastReceiver 启动的 JobIntentService 向用户发送截止日期临近的通知。当另一个截止日期的下一个通知临近时,我只想更新现有通知并将 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());
    }
  }
}   

最佳答案

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();

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

关于Android:如何修复通知的递增 setNumber()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50324255/

相关文章:

android - 通过命令行调用 JUnit 时如何使 takeScreenshot() 在 Robotium 上工作?

android - 使用 Android 语音识别 API

android - 收到推送通知时添加新通知(不替换以前的)

android - 通知自动取消不适用于 Android Lollipop

Android - AWS s3 谷歌登录

android - 单击选项卡(单选按钮)我的内存力加倍

android - 为什么当应用程序处于后台时声音不响(Android应用程序中的Firebase推送通知)?

java - 如果用户正在使用应用程序,那么如何停止显示通知?

android - 如何从 Google Play 服务通知中检测 Intent