Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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+?

like image 249
Michael Avatar asked Sep 08 '16 23:09

Michael


2 Answers

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.

like image 80
CommonsWare Avatar answered Oct 24 '22 22:10

CommonsWare


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
}

or

fun Context.hasSmsPermissionInManifest(): Boolean {
    val packageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)
    val permissions = packageInfo.requestedPermissions

    return permissions?.any { perm -> perm == Manifest.permission.READ_SMS || perm == Manifest.permission.RECEIVE_SMS } ?: false
}
like image 24
Osvel Alvarez Jacomino Avatar answered Oct 24 '22 22:10

Osvel Alvarez Jacomino