Remove all notifications from notification bar

旧巷老猫 提交于 2019-12-09 13:15:32

问题


I want to remove all cancelable notifications from status bar. I know how to remove my app notifications I have seen this post before, butI want to remove other apps notifications.

There is a "Clear" button in notifications in all android versions which clears all notifications with this flag: Notification.FLAG_AUTO_CANCEL

That means it's possible to cancel all notifications. But I haven't found any document about how to do that. Is there anybody guide me how to do that?

Thanks


回答1:


Starting with API Level 18 you can cancel Notifications posted by other apps different than your own using NotificationListenerService, the method changed a little in Lollipop, here is the way to remove notifications covering also Lillipop API.

First inside the onNotificationPosted method you store all the StatusBarNotification objects. Then you should maintain an updated reference to those objects, removing them if the notification is somehow dismissed in onNotificationRemoved method.

@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
    }
}

Finally you can remove any notification using cancelNotification method.

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


来源:https://stackoverflow.com/questions/28667583/remove-all-notifications-from-notification-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!