android - 使用 NotificationListenerService 检查对通知的访问

标签 android notifications

我正在使用 >=4.3 NotificationListenerService 来访问通知。在第一次启动时,我的应用程序将用户带到“访问通知”系统面板,但只要禁用了“访问通知”中我的应用程序的复选框,我想将用户带到那里。我在任何地方都没有找到 isNotificationAccessEnabled() 方法,但我绝对知道这是可能的,因为像 Krome 这样的应用程序也这样做。

最佳答案

2016 年 6 月 15 日编辑

我不确定 the support library 的哪个版本这是添加到的,但现在看起来这个功能是内置的。只需使用:

NotificationManagerCompat.getEnabledListenerPackages(context); (link to docs)

这将返回 Set<String>您可以遍历以找到您的包名称。但是请注意,我没有亲自测试过。但看起来它可能更适合使用它来代替我下面的旧解决方案。


旧解决方案

此代码适用于我的应用:

ContentResolver contentResolver = context.getContentResolver();
String enabledNotificationListeners = Settings.Secure.getString(contentResolver, "enabled_notification_listeners");
String packageName = context.getPackageName();

// check to see if the enabledNotificationListeners String contains our package name
if (enabledNotificationListeners == null || !enabledNotificationListeners.contains(packageName))
{
    // in this situation we know that the user has not granted the app the Notification access permission
    throw new Exception();
}
else
{
    doSomethingThatRequiresNotificationAccessPermission();
}

我看到的 enabledNotificationsListeners 的典型值String看起来像这样:

  • 用户未授予其任何应用通知访问权限
    • null""
  • 用户已授予一个应用通知访问权限
    • "com.woodblockwithoutco.remotecontrollerexample/com.woodblockwithoutco.remotecontrollerexample.RemoteControlService"
  • 用户已授予两个应用通知访问权限
    • "com.scootrnova.android/com.scootrnova.android.ListenerService:com.woodblockwithoutco.remotecontrollerexample/com.woodblockwithoutco.remotecontrollerexample.RemoteControlService"

这个实现非常简单,效果很好:)

附:我想到了使用 this answer 中硬编码的“enabled_notification_listeners”字符串。 .

关于android - 使用 NotificationListenerService 检查对通知的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18097583/

相关文章:

java - 在Android中使用适配器将两个 ListView 合并为一个

Android Soundpool Load(String path, int priority)

android - 通知 Android 3.0

android - Stacked Wear 通知也显示在手机上

android - 如何在 node.js 中使用 express 为 Android 应用程序实现服务器端 session ?

android - TextView字体大小根据不同的分辨率和屏幕大小

java - 硬编码文本问题

android - 在 Android 中通过通知栏复制粘贴

php - 从 web 服务器到客户端 bowers 的实时通知

android - 通知中的 IllegalArgumentException