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

ste*_*pic 8 settings service notifications android

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

startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
Run Code Online (Sandbox Code Playgroud)

我想检查用户是否已授予我的应用程序授权.我已经尝试检查我的NotificationListenerService是否正在运行,但它似乎被系统暂停并重新启动(即使我返回START_STICKY).

ACh*_*hep 22

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

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());
Run Code Online (Sandbox Code Playgroud)

  • 我真的想给你一个饼干!格拉西亚斯. (2认同)

ste*_*pic 8

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

    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;
    }
Run Code Online (Sandbox Code Playgroud)

  • 如果取消选中该权限,则该过程将继续运行.所以这不是防弹,但我没有找到另一种方式. (4认同)
  • 如果我取消选中权限,我的服务就会被销毁.所以上面的答案对我来说非常合适. (2认同)

Ast*_*ixR 5

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

NotificationManagerCompat.getEnabledListenerPackages(Context context)
Run Code Online (Sandbox Code Playgroud)

检查您的侦听器是否已启用。 来源