Check if user has granted NotificationListener acc

2019-03-26 13:16发布

I'm using this code to open Notification Listener Settings:

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

I would like to check if the user has granted authorization to my app. I already tried to check if my NotificationListenerService is running, but it seems that it gets halted and restarted by the system (even if I return START_STICKY).

3条回答
对你真心纯属浪费
2楼-- · 2019-03-26 13:36

If you're using androidx you can use

NotificationManagerCompat.getEnabledListenerPackages(Context context)

to check if your listener is enabled. Source

查看更多
聊天终结者
3楼-- · 2019-03-26 13:42

The only correct way to do it is to check the secure settings:

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());
查看更多
手持菜刀,她持情操
4楼-- · 2019-03-26 13:45

I was wrong, checking if service is running works:

    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;
    }
查看更多
登录 后发表回答