java 如何检查用户是否授予了BIND_NOTIFICATION_LISTENER_SERVICE权限

kmbjn2e3  于 2022-12-17  发布在  Java
关注(0)|答案(2)|浏览(147)

我是Android新手,我正在尝试开发一个应用程序,它可以读取WhatsApp通知并对它们做一些事情:)
我尝试了不同的事情,检查,如果用户授予权限“BIND_NOTIFICATION_LISTENER_SERVICE”,但没有工作。它总是说,该权限不授予。但这不是真的。下面是代码:

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

这是设置,我在应用程序中更改:startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
清单:

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>

收听服务运行的很好。它只是说,我没有权限。(抱歉我的英语不好)

lg40wkob

lg40wkob1#

这是解决方案:

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

ftf50wuq2#

Google为此提供了官方API:

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

相关问题