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

时间:2019-11-22 10:26:31

标签: 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();

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

1 个答案:

答案 0 :(得分:0)

欢迎使用StackOverflow。

您使用的封装似乎已经不再维护,因为它deprecated in favour of AndroidX,如果您的项目可以选择的话,我建议迁移到该封装。

如果我的假设是正确的,那么您尝试做的事情与您在iOS上可以实现的类似,但是Android SDK does not support this out of the box(尽管似乎有a workaround

因此,您正在调用的函数不能用于该特定目的。 setNumber函数sets the number displayed in the long press menu

所有这些

可以更新已发送的通知,并使用setNumber方法更新长按菜单中显示的数字,如in this article

所示

TL; DR:

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

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

  • 再次运行NotificationManagerCompat.notify(),并传递SAME通知ID和NEW通知。

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