androidnotificationsnotification-listener

Clear Non Removable Notifications


I am making notification blocker which removes selected applications Notifications.

I have used the snippet in my Notification Listener Service as,

@Override
public void onNotificationPosted(StatusBarNotification sbn) {
    if(SettingsActivity.SettingsInfo.getInt(sbn.getPackageName(), R.drawable.unblock)==R.drawable.block)
        {
            if(Build.VERSION.SDK_INT<Build.VERSION_CODES.LOLLIPOP) 
               cancelNotification(sbn.getPackageName(), sbn.getTag(), sbn.getId());
            else 
               cancelNotification(sbn.getKey());
        }
}

But this code only clears the cancellable notifications. But I want to remove all notifications of the selected app(also system notifications). Is there any way to do this?

I tried reflection method too.

 NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                        manager.cancel(sbn.getTag(), sbn.getId());
                        Class localClass = Class.forName("android.os.ServiceManager");
                        Method getService = localClass.getMethod("getService", new Class[]{String.class});
                        if (getService != null) {
                            Object result = getService.invoke(localClass, new Object[]{Context.NOTIFICATION_SERVICE});
                            if (result != null) {
                                IBinder binder = (IBinder) result;
                                final INotificationManager iNotificationManager = INotificationManager.Stub.asInterface(binder);
                                int uid = 0;
                                try {
                                    uid = this.getPackageManager().getApplicationInfo(sbn.getPackageName(), 0).uid;
                                } catch (PackageManager.NameNotFoundException e) {
                                    e.printStackTrace();
                                }
                                iNotificationManager.cancelAllNotifications(sbn.getPackageName(), uid);
                            }
                        }

But I am getting Security Exception

as Calling UID gave package owned by other UID

For more details, I want to do like

App ->App Settings -> Notifications -> Block All

Thanks in advance!!!


Solution

  • Thanks for your response, From my research I got the solution

    to clear notifications with flag FLAG_NO_CLEAR

    for api>25, You can snooze notification like

    snoozeNotification(sbn.getKey(), Long.MAX_VALUE);
    

    for api>23 and <26 , there is a method which can be used to ovveride group key and group them to your notifications,

    statusbarnotification.setOverrideGroupKey("key");
    

    for less api's,

    You need root access or system privileges . Then you can use

    iNotificationManager.cancelAllNotifications(sbn.getPackageName(), uid);