【问题标题】:Is there a way an app can check if it is allowed to access notifications?有没有办法让应用程序检查它是否被允许访问通知?
【发布时间】:2021-09-10 14:37:34
【问题描述】:

我想实现一个 NotificationListenerService 来访问所有发布到通知栏的通知。

我了解我需要通过此调用启用对“设置”中的通知的访问:

startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));

有没有办法检查用户是否为我的应用激活了通知访问权限?

【问题讨论】:

标签: android android-notifications


【解决方案1】:

我设法找到了一个小技巧来解决这个问题。如果你查看Settings.Secure的来源,你会看到ENABLED_NOTIFICATION_LISTENERS@hide注解。我不知道这是不是故意的。在一个相关主题上,CommonsWare 在another answer 中确实提到有一个bug 阻止了此设置的启动,所以我想是无意的。

无论如何,要解决这个问题,我所做的只是使用ENABLED_NOTIFICATION_LISTENERS 的字符串值获取当前启用的通知侦听器列表:

String enabledListeners = Settings.Secure.getString(context.getContentResolver(), 
    "enabled_notification_listeners");

然后您只需检查您的服务是否在列表中。

我尚未在所有 API >= 18 上对此进行测试,但它可以在 Android 4.4.2 上运行。

【讨论】:

  • 检查您的服务是否在列表中非常简单,请在此处查看我的答案:stackoverflow.com/a/21392852/823952
  • 在 4.4.4 上对我不起作用,但我在 Genymotion Emulator 上试过
【解决方案2】:

可能适用于 API 19 (4.4) 及更高版本。 虽然我尝试过 API 21 (5.0)

String enabledListeners = Settings.Secure.getString(context.getContentResolver(), 
"enabled_notification_listeners");

“安全”变成了红色。如果你想使用它,你必须使用:

String enabledNotificationListeners = 
  android.provider.Settings.Secure.getString(context.getContentResolver(), 
  "enabled_notification_listeners");

【讨论】:

    【解决方案3】:

    试试:

    NotificationManagerCompat.from(context).areNotificationsEnabled()
    

    【讨论】:

    • 这是为了检查您的通知是否被 Android 应用户请求阻止。问题是关于 NotificationListenerService(检查您是否可以收听通知)。
    【解决方案4】:

    在您的服务类中使用 listnerConnected 布尔值

    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;
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 2011-08-15
      • 1970-01-01
      • 2015-11-18
      相关资源
      最近更新 更多