Android 11中使用ACTION_GET_CONTENT如何获取File对象
Android 10(API 29)引入分区存储机制后,系统限制第三方应用直接访问其他应用/公共目录下的文件真实路径,你用到的MediaStore.Images.Media.DATA字段已被官方废弃,通过ACTION_GET_CONTENT获取的Content Uri本身不会暴露原始路径,因此原有解析方法完全失效。
不需要强行从Content Uri解析原始路径,你可以通过复制输入流到应用私有目录的方式拿到可正常使用的File对象,该方案适配全版本Android系统,且无需申请额外存储权限:
public File getPdfFileFromUri(Context context, Uri uri) throws IOException { // 在应用私有缓存目录创建临时PDF文件,无需存储权限即可读写 File tempPdf = new File(context.getCacheDir(), "temp_" + System.currentTimeMillis() + ".pdf"); InputStream is = null; OutputStream os = null; try { is = context.getContentResolver().openInputStream(uri); os = new FileOutputStream(tempPdf); byte[] buffer = new byte[4096]; int readLen; while ((readLen = is.read(buffer)) > 0) { os.write(buffer, 0, readLen); } os.flush(); return tempPdf; } finally { if (is != null) { try { is.close(); } catch (IOException ignore) {} } if (os != null) { try { os.close(); } catch (IOException ignore) {} } } }
注意事项
- 原有方法的错误不仅是存储机制变更导致,你用了图片媒体库的
MediaStore.Images.Media.DATA字段查询PDF文件,本身逻辑就不适用。 - 临时文件如果不需要长期留存,用完后主动删除即可,避免占用应用缓存空间。
- Android 11及以上版本即便申请了所有文件访问权限,依旧无法直接获取第三方应用/公共目录下非自身创建文件的路径,复制流是目前唯一通用稳定的处理方案。
内容的提问来源于stack exchange,提问作者user5957595
相关产品推荐
相关产品推荐

