Binozo
Binozo

Reputation: 151

How to check, if user granted BIND_NOTIFICATION_LISTENER_SERVICE Permission

I am new to Android and I am trying to develop an app, which reads Whatsapp Notifications and does something with them :)

I tried different things, to check, if user granted the permission "BIND_NOTIFICATION_LISTENER_SERVICE" But nothing worked. It always said, that the permission isn't granted. But that isn't true. Here is the code:

        if(ContextCompat.checkSelfPermission(this, Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE) == PackageManager.PERMISSION_GRANTED){
            Log.i(TAG, "App has permission!");
        } else
            Log.i(TAG, "App hasn't permission " + ContextCompat.checkSelfPermission(this, Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE));

That are the settings, which I changed in the App: startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));

Manifest:

            android:label="Whatsapp Nachrichten leser"
            android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
            <intent-filter>
                <action android:name="android.service.notification.NotificationListenerService" />
            </intent-filter>
        </service>

The Listener-Service works perfectly. It only sais, I don't have the permission. (Sorry for my bad english)

Upvotes: 4

Views: 1990

Answers (2)

Saket
Saket

Reputation: 3086

Google offers an official API for this:

NotificationManagerCompat.getEnabledListenerPackages(context).contains(context.packageName)

Upvotes: 3

Binozo
Binozo

Reputation: 151

This is the solution:

private boolean isNotificationServiceEnabled(Context c){
        String pkgName = c.getPackageName();
        final String flat = Settings.Secure.getString(c.getContentResolver(),
                "enabled_notification_listeners");
        if (!TextUtils.isEmpty(flat)) {
            final String[] names = flat.split(":");
            for (int i = 0; i < names.length; i++) {
                final ComponentName cn = ComponentName.unflattenFromString(names[i]);
                if (cn != null) {
                    if (TextUtils.equals(pkgName, cn.getPackageName())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

Upvotes: 7

Related Questions