Android 8.0通知栏权限开启适配

使用手机时,我们经常会碰到各种通知,例如微信,QQ,浏览器等等,不厌其烦的给你各种推送,本文将演示通知的大致流程

首先,我们在一个适当的时机检查我们App的通知栏权限

boolean Jurisdiction = NotificationManagerCompat.from(AppApplication.getContext()).areNotificationsEnabled();

通过这个方法,我们能够获取到我们App是否有通知栏的推送权限,如果我们没有权限就使用引导的方式来告诉用户我们需要一个这样的权限,并提供设置的方式,这里我使用了第三方material-dialogs开源弹窗框架。最后在弹窗的确认监听中根据系统版本号使用对应的方式弹出系统权限管理窗口。当然,你也可以使用你自己的弹窗来提示用户

依赖如下:

api "com.afollestad.material-dialogs:core:0.9.4.5"
api "com.afollestad.material-dialogs:commons:0.9.4.5"
if (!NotificationManagerCompat.from(AppApplication.getContext()).areNotificationsEnabled()) {
    MaterialDialog.Builder builder = new MaterialDialog.Builder(mContext)
        .title("请手动将通知打开")
        .positiveText("确定")
        .negativeText("取消");
        .onAny(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.NEUTRAL) {
                    Log.e("onClick", "更多信息: ");
                } else if (which == DialogAction.POSITIVE) {
                    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.VERSION.SDK_INT <  Build.VERSION_CODES.O) {
                        Intent intent = new Intent();
                        intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                        intent.putExtra("app_package", MainActivity.this.getPackageName());
                        intent.putExtra("app_uid", MainActivity.this.getApplicationInfo().uid);
                        startActivity(intent);
                    } else if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
                        Intent intent = new Intent();
                        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.addCategory(Intent.CATEGORY_DEFAULT);
                        intent.setData(Uri.parse("package:" + MainActivity.this.getPackageName()));
                        startActivity(intent);
                    } else {
                        Intent localIntent = new Intent();
                        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                        localIntent.setData(Uri.fromParts("package", MainActivity.this.getPackageName(), null));
                        startActivity(localIntent);
                    }
                    Log.e("onClick", "同意: ");
                } else if (which == DialogAction.NEGATIVE) {
                    Log.e("onClick", "不同意: ");
                }
            }
        }).show();
    }

到此,我们的权限已经可以保证开启了。下一篇:发起推送

猜你喜欢

转载自blog.csdn.net/LikeBoke/article/details/83929711