如何在不发送通知的情况下以编程方式更改应用通知徽章计数 (java/android)



我想在用户每次到达主页(或按下按钮进行测试(时更改通知徽章计数。我现在能做到这一点的唯一方法是发送这样的通知:

Notification notification = new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
  .setContentTitle("New Messages")
  .setContentText("You've received 3 new messages.")
  .setSmallIcon(R.drawable.ic_notify_status)
  .setNumber(messageCount)
  .build();

但是,我想在不发送通知的情况下更改徽章计数,因为我不想弄乱通知面板。

欢迎来到 StackOverflow。

看起来您正在使用的 pacakge 不再得到维护,因为它已被弃用以支持 AndroidX,如果它是您项目的一个选项,我建议迁移到它。

如果我的假设是正确的,您正在尝试做一些类似于您在iOS上可以实现的事情,但是Android SDK不支持开箱即用,尽管似乎有一种解决方法

因此,您调用的函数不能用于该特定目的。setNumber功能设置长按菜单中显示的数字

说了这么多

您可以更新已发送的通知,并使用 setNumber 方法更新长按菜单中显示的数字,如本文中所述

TL;博士:

  • 使用以下方法发布带有标识符的通知,并将标识符保存在某个位置供以后使用:NotificationManagerCompat.notify(notificationId, builder.build());

  • 重新运行您在问题中发布的相同代码,并在此过程中更新徽章编号

  • 再次运行NotificationManagerCompat.notify(),传递相同的通知 ID 和新的通知。

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
int notificationID = 123456;
int messageCount = 1;
Notification notification = new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
        .setContentTitle("New Messages")
        .setContentText("You've received 3 new messages.")
        .setSmallIcon(R.drawable.ic_notify_status)
        .setNumber(messageCount)
        .build();
notificationManager.notify(notificationID, notification);
//Now update the message count
messageCount++;
Notification notification = new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
        .setContentTitle("New Messages")
        .setContentText("You've received 3 new messages.")
        .setSmallIcon(R.drawable.ic_notify_status)
        .setNumber(messageCount)
        .build();
notificationManager.notify(notificationID, notification);

最新更新