当 Android 应用程序在 Android 上打开时如何重置徽章计数

Jim*_*nts 5 android

打开应用程序后,我希望删除徽章计数。目前,只有当我通过锁定屏幕中的推送消息打开应用程序时,它才会被删除。然后推送消息将从锁定屏幕中删除,因此我也可以将这个问题表述为“如何从锁定屏幕中删除推送消息”。

使用此代码我可以检索通知:

@Override
protected void onStart() {
    super.onStart();
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        StatusBarNotification[] notifications = notificationManager.getActiveNotifications();
        for (StatusBarNotification statusBarNotification : notifications) {
            statusBarNotification.getNotification().number = 0;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但当将数字设置为 0 时,没有任何反应。

Jim*_*nts 7

正确答案由@Alex Kamenkov 提交。

   @Override
    protected void onStart() {
        super.onStart();
        resetBadgeCounterOfPushMessages();
    }

    private void resetBadgeCounterOfPushMessages() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            if (notificationManager != null) {
                notificationManager.cancelAll();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)