简体   繁体   中英

Check if READ_EXTERNAL_STORAGE permission is needed to to read from specific Uri

I would like to check if I need Manifest.permission.READ_EXTERNAL_STORAGE to read from given Uri.

This is needed to properly handle incoming Intents to my app. For example, if I share image to my app from WhatsApp and my app doesn't have read permission that's OK. I still can read from this Uri since WhatsApp granted me permission to read this Uri. Google Photos, however, share Uris as an external storage Uri and to read from it I need to prompt user to give my app permission to read from external storage.

I know I could always ask user to provid my app read permission but I would like to avoid this whenever possible.

I'm not sure if this is the best way to handle it but you can catch the SecurityException and then request requisite permissions:

try {
    getContentResolver().query(uri, ...);
} catch (SecurityException e) {
    // Request storage perms here
    ActivityCompat.requestPermissions(this, new String[] {
        Manifest.permission.READ_EXTERNAL_STORAGE
    }, REQ_READ_STORAGE_PERMISSION);
}
    if( PERMISSION_GRANTED != checkUriPermission( uri, android.os.Process.myPid(), android.os.Process.myUid(),
            Intent.FLAG_GRANT_READ_URI_PERMISSION)) {
        // request permission here
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM