首页 > 解决方案 > 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,但事实证明,找到教程也很困难。

谁能指出我正确的方向?

标签: androidandroid-permissionsfilenotfoundexceptionandroid-fileprovider

解决方案


推荐阅读