Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if user has granted NotificationListener access to my app

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).

like image 320
stepic Avatar asked Nov 22 '13 09:11

stepic


People also ask

What is listener service on android?

A service that receives calls from the system when new notifications are posted or removed, or their ranking changed.

What is Notification listener in android?

A notification listener service allows the Google App to intercept notifications posted by other applications. Notification Options in the Google App Notification Listener Services. Within the Android Manifest file is the inclusion of the new Notification Listener Service.

How do I use notification listener?

You need to grant access to your app to read notifications: "Settings > Security > Notification access" and check your app. Show activity on this post. Inside the NotificationListenerService you need a looper to communicate with GUI thread so you can create a broadcast to handle the GUI interaction.


3 Answers

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());
like image 153
AChep Avatar answered Oct 05 '22 22:10

AChep


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;
    }
like image 26
stepic Avatar answered Oct 05 '22 23:10

stepic


If you're using androidx you can use

NotificationManagerCompat.getEnabledListenerPackages(Context context)

to check if your listener is enabled. Source

like image 25
AsterixR Avatar answered Oct 06 '22 00:10

AsterixR