以编程方式从 android 中的清单.xml中检索权限

我必须以编程方式从android应用程序的清单.xml中检索权限,我不知道该怎么做。

我在这里阅读了这篇文章,但我对答案并不完全满意。我想在android API中应该有一个类,它允许从清单中检索信息。

谢谢。


答案 1

您可以使用 PackageManager 获取应用程序请求的权限(可能未被授予):

PackageInfo info = getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS);
String[] permissions = info.requestedPermissions;//This array contains the requested permissions.

我已经在实用程序方法中使用它来检查是否声明了预期的权限:

//for example, permission can be "android.permission.WRITE_EXTERNAL_STORAGE"
public boolean hasPermission(String permission) 
{
    try {
        PackageInfo info = getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS);
        if (info.requestedPermissions != null) {
            for (String p : info.requestedPermissions) {
                if (p.equals(permission)) {
                    return true;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

答案 2

这里有一个有用的实用程序方法可以做到这一点(在Java和Kotlin中)。

爪哇岛

public static String[] retrievePermissions(Context context) {
    final var pkgName = context.getPackageName();
    try {
        return context
                .getPackageManager()
                .getPackageInfo(pkgName, PackageManager.GET_PERMISSIONS)
                .requestedPermissions;
    } catch (PackageManager.NameNotFoundException e) {
         return new String[0];
         // Better to throw a custom exception since this should never happen unless the API has changed somehow.
    }
}

科特林

fun retrievePermissions(context: Context): Array<String> {
    val pkgName = context.getPackageName()
    try {
        return context
                .packageManager
                .getPackageInfo(pkgName, PackageManager.GET_PERMISSIONS)
                .requestedPermissions
    } catch (e: PackageManager.NameNotFoundException) {
        return emptyArray<String>()
        // Better to throw a custom exception since this should never happen unless the API has changed somehow.
    }
}

你可以从这个要点中得到一个工人阶级


推荐