Remove all notifications from notification bar

前端 未结 2 971
后悔当初
后悔当初 2021-02-15 12:47

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 notificatio

2条回答
  •  误落风尘
    2021-02-15 13:14

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

提交回复
热议问题