检查是否需要READ_EXTERNAL_STORAGE权限才能从特定的Uri中读取

时间:2017-05-30 09:02:25

标签: android

我想检查是否需要Manifest.permission.READ_EXTERNAL_STORAGE来读取给定的Uri。

这是正确处理我的应用程序的传入Intent所必需的。例如,如果我从WhatsApp与我的应用程序共享图像,而我的应用程序没有读取权限,那就没问题。我仍然可以阅读这个Uri,因为WhatsApp允许我阅读这个Uri。但是,谷歌照片将Uris作为外部存储Uri共享,并且要从中读取,我需要提示用户授予我的应用程序从外部存储读取的权限。

我知道我总是可以要求用户提供我的应用读取权限,但我希望尽可能避免这种情况。

2 个答案:

答案 0 :(得分:1)

我不确定这是否是处理它的最佳方式,但您可以捕获SecurityException然后请求必要的权限:

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);
}

答案 1 :(得分:0)

    if( PERMISSION_GRANTED != checkUriPermission( uri, android.os.Process.myPid(), android.os.Process.myUid(),
            Intent.FLAG_GRANT_READ_URI_PERMISSION)) {
        // request permission here
    }
相关问题