从通知栏中删除所有通知

Remove all notifications from notification bar

我想从状态栏中删除所有可取消的通知。我知道如何删除我的应用程序通知我以前见过这个post,但我想删除其他应用程序通知。

所有 android 版本的通知中都有一个 "Clear" 按钮,用于清除所有带有此标志的通知:Notification.FLAG_AUTO_CANCEL

这意味着可以取消所有通知。但我还没有找到任何关于如何做到这一点的文件。有人指导我怎么做吗?

谢谢

从API 18级开始,您可以使用NotificationListenerService取消其他应用发布的通知棒棒糖 API.

首先在 onNotificationPosted 方法中存储所有 StatusBarNotification 对象。 然后,您应该维护对这些对象的更新引用,如果通知在 onNotificationRemoved 方法中以某种方式被取消,则将其删除。

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class NotificationService extends NotificationListenerService {

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        // Store each StatusBarNotification object
    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        // Delete removed StatusBarNotification objects
    }
}

最后,您可以使用 cancelNotification 方法删除任何通知。

 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    cancelNotification(sbn.getPackageName(), sbn.getTag(), sbn.getId());
}
else {
    cancelNotification(sbn.getKey());
}

删除所有通知:

科特林

val NM = getSystemService(AppCompatActivity.NOTIFICATION_SERVICE) as NotificationManager
NM.cancelAll()

Java

NotificationManager NM = getSystemService(AppCompatActivity.NOTIFICATION_SERVICE) 
NM.cancelAll()