首页 > 解决方案 > 从 Intent.ACTION_GET_CONTENT 读取 Uri 是否需要 READ_EXTERNAL_STORAGE 权限

问题描述

我想知道,如果我启动以下Intent.ACTION_GET_CONTENT

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/zip");
startActivityForResult(intent, RequestCode.REQUEST_CHOOSE_BACKUP_FILE);

并尝试通过以下方式从意图中读取返回的 Uri。

Uri uri = data.getData();

// Figure out extension
ContentResolver contentResolver = getContext().getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
final String extension = mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));

File temp = null;
try {
    temp = File.createTempFile(Utils.getJStockUUID(), "." + extension);
} catch (IOException e) {
    e.printStackTrace();
}

// Delete temp file when program exits.
temp.deleteOnExit();

InputStream inputStream = null;
OutputStream outputStream = null;

try {
    inputStream = getContext().getContentResolver().openInputStream(uri);
    outputStream = new FileOutputStream(temp);

    byte[] buffer = new byte[8 * 1024];
    int bytesRead;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }
} catch (IOException e) {
    Log.e(TAG, "", e);
} finally {
    close(outputStream);
    close(inputStream);
}

是否READ_EXTERNAL_STORAGE需要许可?

我测试了几轮。令我惊讶的是,我可以在不请求READ_EXTERNAL_STORAGE.

我只是想确认在所有类型的情况下READ_EXTERNAL_STORAGE都不需要从 中读取 Uri 。Intent.ACTION_GET_CONTENT

标签: android

解决方案


我遇到过用户安装了第三方文件管理器(File Manager+)的情况,在这种情况下,如果未首先授予 READ_EXTERNAL_STORAGE 权限(仅当他们使用第三方应用程序来选择文件,如果他们使用 Google Drive 或正常的系统选择,它可以在未经许可的情况下正常工作)。

通过在我的一个模拟器上安装 File Manager+ 并试用它,我能够复制这种行为。


推荐阅读