我正在使用>=4.3版本的NotificationListenerService
访问通知。在第一次启动时,我的应用会将用户带到“访问通知”系统面板,但是当“访问通知”中我的应用的复选框被禁用时,我想每次都将用户带到那里。我没有找到isNotificationAccessEnabled()
方法,但我确定这是可能的,因为像Krome这样的应用也可以实现。
我正在使用>=4.3版本的NotificationListenerService
访问通知。在第一次启动时,我的应用会将用户带到“访问通知”系统面板,但是当“访问通知”中我的应用的复选框被禁用时,我想每次都将用户带到那里。我没有找到isNotificationAccessEnabled()
方法,但我确定这是可能的,因为像Krome这样的应用也可以实现。
我不确定这个功能是在哪个版本的support库中添加的,但现在看起来似乎已经内置该功能了。只需使用以下代码:
NotificationManagerCompat.getEnabledListenerPackages(context);
(文档链接)
这将返回一个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"
这个实现非常直接简单,并且表现出色 :)
P.S. 我从此答案中获得使用硬编码的 "enabled_notification_listeners" 字符串的想法。
public static boolean isNotificationAccessEnabled = false;
@Override
public void onListenerConnected() {
isNotificationAccessEnabled = true;
}
@Override
public void onListenerDisconnected() {
isNotificationAccessEnabled = false;
}
@Override
public boolean onUnbind(Intent mIntent) {
boolean mOnUnbind = super.onUnbind(mIntent);
isNotificationAccessEnabled = false;
return mOnUnbind;
}`与在我的主要活动中检查isNotificationAccessEnabled相结合。
- Nick从Android 8.1(SDK 27)开始,您可以在NotificationManager上调用isNotificationListenerAccessGranted。这是正确的API使用方式,而不是接受答案的API。请参见下面的解释。
就像shai tibber已经说过的那样,接受的答案是不正确的。
onListenerConnected()
和onListenerDisconnect()
甚至在没有授予NotificationListener访问权限时也会被调用。因此,依赖于这些回调来设置布尔值将会得到错误的结果。而getEnabledListenerPackages(context)
只会返回所有在其AndroidManifest中定义了启用通知监听器(android:enabled=true)的包。它与用户访问权限没有直接关系。文档正是如此说明:
获取具有已启用通知监听器组件的包集合。
稍作修改后,@Damians的答案可以很好地运行。
public class NotifyListener extends NotificationListenerService{
public static boolean listnerConnected = false;
@Override
public IBinder onBind(Intent intent) {
Log.d(name,"onBind Called");
listnerConnected = true;
return super.onBind(intent);
}
@Override
public void onDestroy()
{
super.onDestroy();
Log.e("destroy", "called");
listnerConnected = false;
}
}
android:enabled="true"
,NotificationManagerCompat.getEnabledListenerPackages(context)
将包括我的包名,无论用户是否授予访问权限。 - P. B.