安卓應(yīng)用開發(fā),在做推送功能時(shí)會(huì)用到推送權(quán)限是否打開的檢測(雖然系統(tǒng)默認(rèn)時(shí)打開的),但是有些用戶可能會(huì)特意關(guān)掉(尤其時(shí)測試人員),那么如何獲取到用戶手機(jī)推送權(quán)限的狀態(tài)呢,在網(wǎng)上搜到的代碼有以下兩種。
- 1: 親測不準(zhǔn)確不好用
String CHECK_OP_NO_THROW = "checkOpNoThrow";
String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";
AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
ApplicationInfo appInfo = context.getApplicationInfo();
String pkg = context.getApplicationContext().getPackageName();
int uid = appInfo.uid;
Class appOpsClass = null;
/* Context.APP_OPS_MANAGER */
try {
appOpsClass = Class.forName(AppOpsManager.class.getName());
Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
String.class);
Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
int value = (Integer) opPostNotificationValue.get(Integer.class);
return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);
} catch (Exception e) {
e.printStackTrace();
}
- 2 有效可用 推薦使用
NotificationManagerCompat manager = NotificationManagerCompat.from(App.getInstance().getContext());
boolean isOpened = manager.areNotificationsEnabled();
要注意的是,areNotificationsEnabled方法的有效性官方只最低支持到API 19,低于19的仍可調(diào)用此方法不過只會(huì)返回true,即默認(rèn)為用戶已經(jīng)開啟了通知。
如果用戶關(guān)閉了推送權(quán)限此時(shí)需要提示用戶打開app詳情頁打開權(quán)限,代碼如下:
// 根據(jù)isOpened結(jié)果,判斷是否需要提醒用戶跳轉(zhuǎn)AppInfo頁面,去打開App通知權(quán)限
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", App.getInstance().getApplication().getPackageName(), null);
intent.setData(uri);
startActivity(intent);