有圖有真相怜庸,首先到設(shè)置里邊關(guān)閉該應(yīng)用的通知開關(guān):在android應(yīng)用中钮追,有時候會用到系統(tǒng)通知是否開啟的狀態(tài)预厌,以便進行下一步操作,所以元媚,獲取到狀態(tài)是很有必要的轧叽,之前一直苦于找不到合適的方法來解決苗沧,因為畢竟涉及到系統(tǒng),不好辦炭晒,今日看到大神支招待逞,試了一下,很好用网严,貼出來识樱,大家看,干了這碗安利震束!
代碼量很少胸懈,但是很精辟担扑,就一個工具類恰响,用到了java反射原理
public class NotificationsUtils {
private static final String CHECK_OP_NO_THROW = "checkOpNoThrow";
private static final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";
public static boolean isNotificationEnabled(Context context) {
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 = (int)opPostNotificationValue.get(Integer.class);
return ((int)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;
}
}