Android 检查用户是否已授予NotificationListener对我的应用程序的访问权限

Android 检查用户是否已授予NotificationListener对我的应用程序的访问权限,android,service,notifications,settings,Android,Service,Notifications,Settings,我正在使用以下代码打开通知侦听器设置: startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS")); 我想检查用户是否已授权我的应用程序。 我已经尝试检查NotificationListenerService是否正在运行,但系统似乎会停止并重新启动它(即使我返回START\u STICKY)。我错了,检查服务是否正在运行有效: private boolean isNLServic

我正在使用以下代码打开通知侦听器设置:

startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
我想检查用户是否已授权我的应用程序。
我已经尝试检查NotificationListenerService是否正在运行,但系统似乎会停止并重新启动它(即使我返回START\u STICKY)。

我错了,检查服务是否正在运行有效:

    private boolean isNLServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
             if (NLService.class.getName().equals(service.service.getClassName())) {
                  return true;
             }
        }

        return false;
    }

唯一正确的方法是检查安全设置:

ComponentName cn = new ComponentName(context, YourNotificationListenerService.class);
String flat = Settings.Secure.getString(context.getContentResolver(), "enabled_notification_listeners");
final boolean enabled = flat != null && flat.contains(cn.flattenToString());

如果您使用的是androidx,您可以使用

NotificationManagerCompat.getEnabledListenerPackages(Context context)
检查您的侦听器是否已启用。

如果取消选中权限,则进程将继续运行。所以这不是防弹的,但我还没有找到其他方法。如果我取消选中权限,我的服务就会被破坏。所以上面的答案对我来说非常有效。我真的想给你一块饼干!格雷西亚斯,这很有效。您也可以通过这种方式检查AccessibilityService,但需要将
“enabled\u accessibility\u services”
传递到
设置.Secure.getString()
。这两个字符串都在Settings.Secure中设置为常量,但用于通知的字符串由于某种原因被隐藏。无法工作。虽然它已经被批准-此代码返回FALSE我使用了此解决方案,它工作正常: