當(dāng)APP有推送功能時(shí),需要判斷當(dāng)前app在手機(jī)中是否開啟了允許消息推送,否則即使添加了推送代碼仍然收不到通知
private boolean isNotificationEnabled(Context context) {
boolean isOpened = false;
try {
isOpened = NotificationManagerCompat.from(context).areNotificationsEnabled();
} catch (Exception e) {
e.printStackTrace();
isOpened = false;
}
return isOpened;
}
沒錯(cuò)道伟,只有一行代碼葫松。
Api24以上,NotificationManagerCompat中提供了areNotificationsEnabled()方法胁艰。該方法中已經(jīng)對(duì)API19以下款筑,API19-24,API24以上腾么,這三種情況做了判斷奈梳。直接使用其返回值即可。
該方法如果返回true表示打開了消息通知解虱,如果返回false則沒有打開攘须。沒有打開則跳轉(zhuǎn)設(shè)置界面。代碼如下:
private void gotoSet() {
Intent intent = new Intent();
if (Build.VERSION.SDK_INT >= 26) {
// android 8.0引導(dǎo)
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中進(jìn)行判斷:
//判斷該app是否打開了通知饭寺,如果沒有的話就打開手機(jī)設(shè)置頁面
if (!isNotificationEnabled()) {
gotoSet();
} else {
//當(dāng)前app允許消息通知
}