Is there a way to check for manifest permission from code?

試著忘記壹切 提交于 2019-12-30 00:57:09

问题


How do I check for a specific permission in the manifest.xml from code? I want to throw some exception if some permissions that are necessay for my application are missing.

For example, FINE_LOCATION and COARSE_LOCATION I know that android will also throw an exception on the launch of the specific activiy that is using GPS, but I need to check the manifest and throw an exception at the launch of the application itself. This holds not only for location access, but also for other permissions.

Any suggestions would be helpful.


回答1:


You can check whether the permission is granted or not for specific permission by using PackageManager. For example

    PackageManager pm = getPackageManager();
    if (pm.checkPermission(permission.FINE_LOCATION, getPackageName()) == PackageManager.PERMISSION_GRANTED) {
        // do something
    } else {
        // do something
    }



回答2:


You can read the available <uses-permission> tags at runtime using the following. Tested on older Android versions AND Android 6 and 7

PackageManager pm = getPackageManager();
try
{
    PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), PackageManager.GET_PERMISSIONS);
    String[] requestedPermissions = null;
    if (packageInfo != null) {
        requestedPermissions = packageInfo.requestedPermissions;
    }

    if (requestedPermissions != null && requestedPermissions.length > 0)
    {
        List<String> requestedPermissionsList = Arrays.asList(requestedPermissions);
        ArrayList<String> requestedPermissionsArrayList = new ArrayList<String>();
        requestedPermissionsArrayList.addAll(requestedPermissionsList);

        Log.i(ExConsts.TAG, ""+requestedPermissionsArrayList);
    }
}
catch (PackageManager.NameNotFoundException e)
{
    e.printStackTrace();
}


来源:https://stackoverflow.com/questions/8292558/is-there-a-way-to-check-for-manifest-permission-from-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!