我正在使用 >=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/