源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Android如何获取系统通知的开启状态详解

  • 时间:2022-03-06 21:39 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Android如何获取系统通知的开启状态详解
[b]前言[/b] 大家应该都有所体会,平常在android应用中,有时候会用到系统通知是否开启的状态,以便进行下一步操作,所以,获取到状态是很有必要的,之前一直苦于找不到合适的方法来解决,因为毕竟涉及到系统,不好办,今日看到大神支招,试了一下,很好用,话不多少了,来一起看看详细的介绍吧。 [b]有图有真相,首先到设置里边关闭该应用的通知开关:[/b] [img]http://files.jb51.net/file_images/article/201708/201788102747917.png?201778102757[/img] [b]然后在应用中,点击按钮,获取状态:[/b] [img]http://files.jb51.net/file_images/article/201708/201788102818306.png?201778102827[/img] [b]这时候,回到设置里,打开通知按钮:[/b] [img]http://files.jb51.net/file_images/article/201708/201788102847207.png?201778102856[/img] [b]再次点击应用中的测试按钮,可以看到,通知已经可用了:[/b] [img]http://files.jb51.net/file_images/article/201708/201788102913060.png?201778102920[/img] [b]代码量很少,但是很精辟,就一个工具类,用到了java反射原理:[/b]
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;
 }
}
[b]总结[/b] 好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程素材网的支持。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部