How to know whether Notifications are enabled or not for an application in android?

前端 未结 2 1403
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-02 00:30

I\'ve a ListView which has the list of installed applications and for each application, I need to know whether the notifications are enabled or not. Currently I\'m using bel

相关标签:
2条回答
  • 2021-01-02 00:55

    See if you can use NotificationManagerCompat.areNotificationsEnabled() https://developer.android.com/reference/android/support/v4/app/NotificationManagerCompat.html#areNotificationsEnabled()

    Android 4.1: How to check notifications are disabled for the application?

    0 讨论(0)
  • 2021-01-02 01:08

    I am afraid this is only possible for the current application. That is why the public API of NotificationManager has the function areNotificationsEnabled() for the current package.

    When looking into android source code, I found AppNotificationSettings - application notification settings. The first switch indicates, whether notifications are blocked or not. The switch listener is here, which points to NotificationBackend. In this class, there is method:

    public boolean getNotificationsBanned(String pkg, int uid)

    which uses INotificationManager ( a class generated from .aidl file during compilation) and it's method:

    boolean areNotificationsEnabledForPackage(String pkg, int uid);

    This is Android private API, cannot be simply invoked. So I tried reflection:

    try {
        NotificationManager mNotificationManager = null;
        Class<?> c = Class.forName("android.app.NotificationManager");
        Method method = c.getMethod("getService");
        Object obj = method.invoke(mNotificationManager);
        Class<?> clazz = Class.forName("android.app.INotificationManager$Stub$Proxy");
        Method areNotificationsEnabledForPackage = clazz.getMethod("areNotificationsEnabledForPackage", String.class, int.class);
        boolean blocked = (boolean) areNotificationsEnabledForPackage.invoke(obj, getPackageName(), android.os.Process.myUid());
        Log.d(MainActivity.class.getSimpleName(), String.valueOf(blocked));
    } catch (Exception e) {
        e.printStackTrace();
    }
    

    However, as you can see, you must first create NotificationManager. Sadly, this class is created for package. So the code above will for only for :

    boolean blocked = (boolean) areNotificationsEnabledForPackage.invoke(obj, getPackageName(), android.os.Process.myUid());
    

    however this will not work :

    //InvocationTargetException will be thrown.
    boolean blocked = (boolean) areNotificationsEnabledForPackage.invoke(obj, "com.android.camera", 10040);
    

    Conclusion:

    Cannot be done.

    0 讨论(0)
提交回复
热议问题