android - Android Q - 外部存储 (FileNotFoundException) 访问被拒绝
问题描述
我的应用程序具有允许上传和下载照片(一次一张)的功能。我对 Pie 及以上版本没有任何问题(minSdk 21)。但是,在将我的应用程序更新为针对 Android Q 后,我不再可以拍照或下载照片。我不断收到 FileNotFoundException:
java.io.FileNotFoundException: /storage/emulated/0/Pictures/mydirectory/IMG_20190924_135818.jpg: open failed: EACCES (Permission denied)
下载
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File downloadedPhoto = FileUtils.createFile(dir, photoDto.getFileName(), photoDto.getBytes());
使用相机上传
Uri contentURI = FileProvider.getUriForFile(PhotosActivity.this, BuildConfig.FILE_PROVIDER_AUTHORITY, PhotoUtils.getPhotoUploadCameraImageTemporaryFile(getFilesDir()));
try (Cursor cursor = getContentResolver().query(contentURI, null, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
String size = cursor.isNull(sizeIndex) ? "Unknown" : cursor.getString(sizeIndex);
String fileType = getContentResolver().getType(contentURI);
File dir = PhotoUtils.getPhotoAlbumDirectory(PhotosActivity.this);
File capturedImageFile = PhotoUtils.createPhotoUploadFile(dir);
PhotoUtils.copyPhotoToTemporaryFile(PhotosActivity.this, contentURI, dir, capturedImageFile);
....
仅供参考,在创建下载的文件和复制到临时文件时会发生异常。我看到 getExternalStoragePublicDirectory 现在已被弃用,所以我认为这是问题的一部分。有人建议用 getExternalFilesDir 替换它,但如果用户卸载应用程序,我需要确保照片保留在设备上。我还拥有读取/写入外部存储和相机的权限,所以我认为这与此无关。
我正在尝试寻找有关如何迁移到“新方式”的示例,但我遇到了困难。甚至 Android 网站上“范围访问”文档的链接也会返回 404。从我所读到的内容来看,似乎我需要迁移到使用 MediaStore,但事实证明,找到教程也很困难。
谁能指出我正确的方向?
解决方案
推荐阅读
- mysql - Sql:加入2个没有公共字段的表
- javascript - 以角度单击按钮后未触发 ngOnDestroy
- sails.js - 尝试在模型上实施关系后,Sails Lift 停止工作
- mysql - 如何从 Python 3 将值插入 Mysql 表中的 DATE 列
- javascript - xml中的自闭标签空间问题 - Cheerio
- nginx - Nginx 与 openssl 构建错误 CentOS 7 -“基本名称:缺少操作数”
- c++ - 为什么在向量包围的向量上使用 .pushback 时出现重叠错误
- docker - 在代码中检索当前环境(Kotlin、Docker)
- sapui5 - 如何在 XML 中绑定嵌套的 JSON 数据
- android-studio - 在 Android Studio 中通过 Retrofit 获得多个 json 响应