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);
    }

更多内容参考这里

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值