gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:56:31 25 4
gpt4 key购买 nike

我使用从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com