Android 之获取系统通知开启状态

约 1506 字 更新于 2026-11-18 5iyo.com

Android 之获取系统通知开启状态

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

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

Android 之获取系统通知开启状态 示意图 Android 之获取系统通知开启状态 示意图

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

Android 之获取系统通知开启状态 示意图 Android 之获取系统通知开启状态 示意图

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

   }

}

投稿作者:赵伟伟

联系邮箱:865397504@qq.com