转载自https://blog.csdn.net/rocrocflying/article/details/78333256?locationNum=8&fps=1
和 https://blog.csdn.net/weixin_30512027/article/details/80859934
没有取得作者授权,如有不便,请联系我删除。
很多人或系统会关闭消息通知权限来组织手机天天就知道“叮咚叮咚”地响,但是开发者也没有办法,牛逼的大佬都是大不了自己写一个,像我这样菜,只能恳求用户打开通知权限了。
首先要判断当前App的通知是否已经打开了:
NotificationManagerCompat notification = NotificationManagerCompat.from(this);
boolean isEnabled = notification.areNotificationsEnabled();
最后返回一个boolean值,true表示权限已经打开,false未打开。接下来就是,当未打开权限的情况下,怎么跳转到设置界面引导用户打开通知:
if (!isEnabled) {
//未打开通知
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle("提示")
.setMessage("请在“通知”中打开通知权限")
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Intent intent = new Intent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("android.provider.extra.APP_PACKAGE", LoginActivity.this.getPackageName());
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //5.0
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("app_package", LoginActivity.this.getPackageName());
intent.putExtra("app_uid", LoginActivity.this.getApplicationInfo().uid);
startActivity(intent);
} else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { //4.4
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + LoginActivity.this.getPackageName()));
} else if (Build.VERSION.SDK_INT >= 15) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
intent.setData(Uri.fromParts("package", LoginActivity.this.getPackageName(), null));
}
startActivity(intent);
}
})
.create();
alertDialog.show();
alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK);
}
这样就可以跳转到设置界面了。