checking if notifications are enabled for specific

2019-08-27 00:32发布

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?

1条回答
再贱就再见
2楼-- · 2019-08-27 00:49

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();
}
查看更多
登录 后发表回答