我想知道,如果我启动以下
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
的情况下成功读取。
我只是想确认,在所有类型的情况下,从 Intent.ACTION_GET_CONTENT
读取 Uri 确实不需要 READ_EXTERNAL_STORAGE
权限。
ACTION_GET_CONTENT
实现中的 bug 可能会迫使你保持该权限。 - CommonsWare/storage/emulated/0/Download/jstock_backup_12-jun-2018.zip
。不需要权限的 Uri 看起来像/document/acc=1;doc=3566
或/document/454
。 - Cheok Yan Chengfile
方案,则可能需要该权限。 - CommonsWare