0

I'm developing a system application and I need to check from my application if a certain package has notifications enabled or not.

I've been triying this code:

public static boolean isNotificationEnabled(Context context) {

    AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);

    ApplicationInfo appInfo = context.getApplicationInfo();

    String pkg = context.getApplicationContext().getPackageName();

    int uid = appInfo.uid;

    Class appOpsClass = null; /* Context.APP_OPS_MANAGER */

    try {

        appOpsClass = Class.forName(AppOpsManager.class.getName());

        Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class);

        Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
        int value = (int)opPostNotificationValue.get(Integer.class);

        return ((int)checkOpNoThrowMethod.invoke(mAppOps,value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    return false;
}

The issue is that it is returning true all the time. What am I doing wrong?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Aldridge1991
  • 1,326
  • 6
  • 24
  • 51
  • Don't believe that will be possible. As far as I know there is a private API for that but as explained here: https://stackoverflow.com/questions/39832714/how-to-know-whether-notifications-are-enabled-or-not-for-an-application-in-andro not possible to check other apps. – Estevex Feb 15 '19 at 09:23
  • Does this answer your question? [Android 4.1: How to check notifications are disabled for the application?](https://stackoverflow.com/questions/11649151/android-4-1-how-to-check-notifications-are-disabled-for-the-application) – sai Pavan Kumar Apr 19 '20 at 17:09

1 Answers1

0

If your method gets Context of the target application (which you want to check if notifications enabled).

You can create NotificationManagerCompat instance based on this Context and check if notifications are enabled for that application:

public static boolean isNotificationEnabled(Context context) {
    return NotificationManagerCompat.from(context.getApplicationContext())
            .areNotificationsEnabled();
}
Denysole
  • 3,903
  • 1
  • 20
  • 28