You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android:如何修复Notification的setNumber()计数递增问题?

问题分析与解决方案

嘿,我一眼就看出问题所在啦!你的totalMessages是AlarmService的成员变量,但JobIntentService每次处理任务时,可能会创建新的服务实例——这意味着每次触发提醒,totalMessages都会被重新初始化为0,执行++totalMessages后自然永远是1,根本没法累积计数。

要解决这个问题,我们需要把计数做持久化存储,比如用Android自带的SharedPreferences,这样不管服务是不是新实例,都能读取到上一次的计数并正确递增。

修改后的代码

把你原来的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);
        }
    }

    // 从SharedPreferences读取当前计数,默认值为0
    SharedPreferences prefs = getSharedPreferences("NotificationPrefs", MODE_PRIVATE);
    int totalMessages = prefs.getInt("total_notifications", 0);
    // 计数加1
    totalMessages++;
    // 将更新后的计数保存回SharedPreferences
    prefs.edit().putInt("total_notifications", totalMessages).apply();

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

额外优化(可选)

如果希望用户点击通知后,计数重置为0,可以在MainActivity的onCreate()方法里添加这段代码:

// 用户打开APP后重置通知计数
SharedPreferences prefs = getSharedPreferences("NotificationPrefs", MODE_PRIVATE);
prefs.edit().putInt("total_notifications", 0).apply();

这样下次触发提醒时,计数就会从1重新开始累积啦~

内容的提问来源于stack exchange,提问作者AJW

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:33:06