小兔网

在android应用中,有时候会用到系统通知是否开启的状态,以便进行下一步操作,所以,获取到状态是很有必要的,之前一直苦于找不到合适的方法来解决,因为毕竟涉及到系统,不好办,今日看到大神支招,试了一下,很好用,贴出来,大家看,干了这碗安利!

有图有真相,首先到设置里边关闭该应用的通知开关:

2021071307354612414140

然后在应用中,点击按钮,获取状态:

2021071307354716406551

这时候,回到设置里,打开通知按钮:

2021071307354817438872

再次点击应用中的测试按钮,可以看到,通知已经可用了:

2021071307354918567203

代码量很少,但是很精辟,就一个工具类,用到了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;   }}

投稿作者:赵伟伟

联系邮箱:该邮件地址已受到反垃圾邮件插件保护。要显示它需要在浏览器中启用 JavaScript。