boolean areNotificationsEnabled = mNotificationManagerCompat.areNotificationsEnabled();
if (!areNotificationsEnabled) {
// Because the user took an action to create a notification, we create a prompt to let
// the user re-enable notifications for this application again.
Snackbar snackbar = Snackbar
.make(
mMainRelativeLayout,
"You need to enable notifications for this app",
Snackbar.LENGTH_LONG)
.setAction("ENABLE", new View.OnClickListener() {
@Override
public void onClick(View view) {
// Links to this app's notification settings
openNotificationSettingsForApp();
}
});
snackbar.show();
return;
}
首先通过areNotificationsEnabled查询应用是否有通知权限,如果没有则执行openNotificationSettingsForApp()方法。
private void openNotificationSettingsForApp() {
// Links to this app's notification settings.
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
//这种方案适用于 API 26, 即8.0(含8.0)以上可以用
intent.putExtra(Settings.EXTRA_APP_PACKAGE, getApplicationContext().getPackageName());
intent.putExtra(Settings.EXTRA_CHANNEL_ID, getApplicationInfo().uid);
//这种方案适用于 API21——25,即 5.0——7.1 之间的版本可以使用
intent.putExtra("app_package", pkg);
intent.putExtra("app_uid", uid);
startActivity(intent);
}
通过intent启动系统应用的通知管理界面。