Android检测应用通知权限-适配8.0

一般情况下,Api 19 以前是没有通知管理的,默认都是开启,不用管。

Api 19 – 24 虽加入了通知管理功能,但没有开放检测是否开启了通知的接口,开发者只能用反射来获取权限值。

Api 24 以上,NotificationManager 提供了 areNotificationsEnabled()方法检测通知权限。

support 包已经考虑了以上场景,在 24.1.0 开放了areNotificationsEnabled(),在19以下默认返回true,19-24返回对应反射值,24以上用原生NotificationManager检测。

特殊情况是部分国产机,加入了通知相关定制功能,开发者是无从控制的或检测的,完全瞎子。比如下面这种通知是否显示在 status bar 的管理。

也就是说,大部分情况,我们用:

NotificationManagerCompat.from(context).areNotificationsEnabled() 

可适配除部分国产机以外的大部分机型。特殊机型暂时没办法,有小伙伴知道怎么搞的话求告知。

areNotificationsEnabled源码也很简单,根据sdk的版本老调用不同方法,24及以上调用areNotificationsEnabled,24以下利用反射,19以下就不管了。

/** * Returns whether notifications from the calling package are not blocked. */
    public boolean areNotificationsEnabled() {
        if (Build.VERSION.SDK_INT >= 24) {
            return mNotificationManager.areNotificationsEnabled();
        } else if (Build.VERSION.SDK_INT >= 19) {
            AppOpsManager appOps =
                    (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
            ApplicationInfo appInfo = mContext.getApplicationInfo();
            String pkg = mContext.getApplicationContext().getPackageName();
            int uid = appInfo.uid;
            try {
                Class<?> 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(appOps, value, uid, pkg)
                        == AppOpsManager.MODE_ALLOWED);
            } catch (ClassNotFoundException | NoSuchMethodException | NoSuchFieldException
                    | InvocationTargetException | IllegalAccessException | RuntimeException e) {
                return true;
            }
        } else {
            return true;
        }
    }
    原文作者:太书红叶
    原文地址: https://blog.csdn.net/u014540814/article/details/81626036
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞