項目中用到日程提醒功能,如果應用的通知欄沒有打開,則需要提示用戶前去打開通知欄,判斷通知欄是否打開代碼如下:
private boolean isNotificationEnabled(Context context) {
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 (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return false;
}
返回值爲true時,通知欄打開,false未打開。
以下代碼爲前往設置頁面:
private void goToSet(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
// 進入設置系統應用權限界面
Intent intent = new Intent(Settings.ACTION_SETTINGS);
startActivity(intent);
return;
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 運行系統在5.x環境使用
// 進入設置系統應用權限界面
Intent intent = new Intent(Settings.ACTION_SETTINGS);
startActivity(intent);
return;
}
}
注:測試功能時發現,若在應用設置中關閉app的通知欄/不勾選顯示通知,則Toast無法顯示