Android通知栏打开状态的多版本适配

部分Andorid手机上通知开启状态是默认关闭的,那么就会造成这部分手机收不到发送的通知,推送的到达率不高的情况。
要解决这个问题也不难,首先要判断手机通知栏的开关是否开启,这个在android.support.v4.app包里面提供了NotificationManagerCompat这个类来处理这种情况

 NotificationManagerCompat manager = NotificationManagerCompat.from(this);
 boolean isOpen=manager.areNotificationsEnabled();

我们来看一下areNotificationsEnabled()里面的实现逻辑

    public boolean areNotificationsEnabled() {
        if (VERSION.SDK_INT >= 24) {
            return this.mNotificationManager.areNotificationsEnabled();
        } else if (VERSION.SDK_INT >= 19) {
            AppOpsManager appOps = (AppOpsManager)this.mContext.getSystemService("appops");
            ApplicationInfo appInfo = this.mContext.getApplicationInfo();
            String pkg = this.mContext.getApplicationContext().getPackageName();
            int uid = appInfo.uid;

            try {
                Class<?> appOpsClass = Class.forName(AppOpsManager.class.getName());
                Method checkOpNoThrowMethod = appOpsClass.getMethod("checkOpNoThrow", Integer.TYPE, Integer.TYPE, String.class);
                Field opPostNotificationValue = appOpsClass.getDeclaredField("OP_POST_NOTIFICATION");
                int value = (Integer)opPostNotificationValue.get(Integer.class);
                return (Integer)checkOpNoThrowMethod.invoke(appOps, value, uid, pkg) == 0;
            } catch (NoSuchMethodException | NoSuchFieldException | InvocationTargetException | IllegalAccessException | RuntimeException | ClassNotFoundException var9) {
                return true;
            }
        } else {
            return true;
        }
    }

上面可以看出基本上Android4.4以上的都可以正常判断通知栏开启状态,由于Android4.4以下没有通知栏开关所以默认返回true

若通知栏为关闭状态,不同版本的开启方法如下

    private void open(Context context) {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
            intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
            intent.putExtra("app_package", context.getPackageName());
            intent.putExtra("app_uid", context.getApplicationInfo().uid);
        } else {
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
点赞