Determine whether a permission is present in the manifest with Android 23+

自作多情 提交于 2019-12-11 05:31:20

问题


I am creating a library that needs to check runtime permissions. I have got runtime permissions working fine and understand the use cases without issues.

However I would like to confirm that the developer using our library has added the permission to their manifest.

The library is a location based library and the developer can either enter ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION into the manifest and I need to be able to determine which they have used (or both) at runtime.

I though using the package manager to check permission would work however this always seems to fail:

PackageManager pm = getPackageManager();
int granted = pm.checkPermission(
                      Manifest.permission.ACCESS_COARSE_LOCATION, 
                      getPackageName() );
if (granted == PackageManager.PERMISSION_GRANTED)
{
    // Use coarse for runtime requests
}
// granted is always PackageManager.PERMISSION_DENIED 

Is there some other way to do this in Android v23+?


回答1:


Off the cuff, retrieve the PackageInfo via PackageManager and getPackageInfo(getPackageName(), PackageManager.GET_PERMISSIONS). Then, look at the requestedPermissions array in the PackageInfo for all the <uses-permission>-requested permissions.




回答2:


Thanks to answer of CommonsWare I'm created this method Kotlin to check if SMS permission is present on Manifest

fun hasSmsPermissionInManifest(context: Context): Boolean {

    val packageInfo = context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS)
    val permissions = packageInfo.requestedPermissions

    if (permissions.isNullOrEmpty())
        return false

    for (perm in permissions) {
        if (perm == Manifest.permission.READ_SMS || perm == Manifest.permission.RECEIVE_SMS)
            return true
    }

    return false
}


来源:https://stackoverflow.com/questions/39401699/determine-whether-a-permission-is-present-in-the-manifest-with-android-23

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