如何检查我的应用是否允许显示通知 [英] How to check if my app is allowed to show notification

查看:150
本文介绍了如何检查我的应用是否允许显示通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android设置中,用户可以根据需要关闭通知.那么,有没有什么方法可以像isNotificationAllowed()一样检查我的应用程序是否可以显示通知?以及如何打开android设置页面来引导我的用户打开通知?

In Android settings users can turn off notification if they don't want to. So is there any method that like isNotificationAllowed() to check is my app is allowed to show notification? And how to open android setting page to guide my users to turn on notification?

推荐答案

编辑-新答案:

好像google添加了正确的API调用: NotificationManagerCompat.from(context).areNotificationsEnabled()

Seems like google added the proper API call: NotificationManagerCompat.from(context).areNotificationsEnabled()

旧答案:

对于正在查看此问题的任何人,请注意NotificationListenerService与显示通知"不同. 这是两回事!如果应用有权访问NotificationListenerService,并不表示显示其通知,反之亦然.为了检查用户是否已阻止来自您应用的通知,您可以使用反射:

For anyone who is looking at this question, note that NotificationListenerService is different from "Show Notification". These two are different things! If an app has access to NotificationListenerService does not mean that its notifications are shown and vice versa. In order to check if user has blocked notification from your app or not, you can use reflection:

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() {

    AppOpsManager mAppOps = (AppOpsManager) GlobalContext.getContext().getSystemService(Context.APP_OPS_SERVICE);

    ApplicationInfo appInfo = GlobalContext.getContext().getApplicationInfo();

    String pkg = GlobalContext.getContext().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;
}
}

来源: https://code.google.com/p/android/issues/detail?id = 38482

这篇关于如何检查我的应用是否允许显示通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆