Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 270
Binozo Avatar asked Oct 21 '25 07:10

Binozo


2 Answers

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;
    }
like image 150
Binozo Avatar answered Oct 23 '25 21:10

Binozo


Google offers an official API for this:

NotificationManagerCompat.getEnabledListenerPackages(context).contains(context.packageName)
like image 39
Saket Avatar answered Oct 23 '25 20:10

Saket



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!