詳細検索

Get permissions set for Android apps

Avatar
by furuyamah
2 min read
Tags

Get permissions set for Android apps
Translated from 日本語 • View original
If you use a feature that requires permissions that are not set in the manifest, you will get a merciless SecurityException.
It's so ruthless that it passes through the catch clause.

The fact that this exception occurs means that the manifest and the code do not match, so the code should be corrected!
It may be that you want to check permissions in your code and conditional branching.
For example, publishing as a library.

That's why we'll give you a method to get a list of permissions and a method to check if the permissions you're looking for exist in your manifest.
[code lang="java" light="true"]
   /**
     * Check if the specified permissions are listed in the manifest.
     * 
     * @param checkPermission to investigate permissions
     * @param context
     * @return true: listed / false: not listed
     */
    public boolean hasPermission(String checkPermission, Context context) {
        if (checkPermission == null || context == null) {
            Cases where no arguments are passed
            return false;
        }
        String[] requestedPermissions = getPermissionList(context);
        if (requestedPermissions == null) {
            When no permission is set in the manifest
            return false;
        }
        for (String str : requestedPermissions) {
            if (str.equals(checkPermission)) {
                Cases where there was a permission to investigate
                return true;
            }
        }
        Cases where permissions to investigate did not exist
        return false;
    }

/**
     * Returns a list of permissions listed in the manifest.
     * 
     * List of @return permissions
     */
    public String[] getPermissionList(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS);
        } catch (NameNotFoundException e) {
            return null;
        }
        return packageInfo.requestedPermissions;
    }
[/code]

How it works

[code lang="java" light="true"]
String checkPermisson = "android.permission.READ_PHONE_STATE";

if (hasPermission(checkPermisson, context)) {
    Log.d("TAG", checkPermisson + " exist!");
} else {
    Log.d("TAG", checkPermisson + " not exist!");
}
[/code]

Hope this helps.

Related Articles