Android判断当前应用是否开启消息通知

当APP有推送功能时,需要判断当前app在手机中是否开启了允许消息推送,否则即使添加了推送代码仍然收不到通知

1
2
3
4
5
6
7
8
9
10
private boolean isNotificationEnabled(Context context) {
boolean isOpened = false;
try {
isOpened = NotificationManagerCompat.from(context).areNotificationsEnabled();
} catch (Exception e) {
e.printStackTrace();
isOpened = false;
}
return isOpened;
}

Api24以上,NotificationManagerCompat中提供了areNotificationsEnabled()方法。该方法中已经对API19以下,API19-24,API24以上,这三种情况做了判断。直接使用其返回值即可。

该方法如果返回true表示打开了消息通知,如果返回false则没有打开。没有打开则跳转设置界面。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private void gotoSet() {
Intent intent = new Intent();
if (Build.VERSION.SDK_INT >= 26) {
// android 8.0引导
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());
} else if (Build.VERSION.SDK_INT >= 21) {
// android 5.0-7.0
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("app_package", getPackageName());
intent.putExtra("app_uid", getApplicationInfo().uid);
} else {
// 其他
intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
intent.setData(Uri.fromParts("package", getPackageName(), null));
}
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}

我们可以在Activity的onCreate中进行判断:

1
2
3
4
5
6
//判断该app是否打开了通知,如果没有的话就打开手机设置页面
if (!isNotificationEnabled()) {
gotoSet();
} else {
//当前app允许消息通知
}
坚持原创技术分享,您的支持将鼓励我继续创作!