如何在 Android 10 (Q) 上直接从外部下载目录读取文件

问题描述:

我正在尝试通过执行以下操作从 Android Q 上的下载文件夹中读取文件:

I am trying to read a file from the download folder on Android Q by doing this:

        File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        File f = new File(downloadDir, "some-existing-file");
        if(!f.exists()) {
            throw new IllegalStateException();
        }

        Uri furi = Uri.fromFile(f);
        try {
            ParcelFileDescriptor des = getContentResolver().openFileDescriptor(
                    furi, "r", null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

我还在清单中设置了 android:requestLegacyExternalStorage="true",并请求了 WRITE_EXTERNAL_STORAGEREAD_EXTERNAL_STORAGE 运行时权限.

I also set android:requestLegacyExternalStorage="true" in the manifest, and requested WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE runtime permissions.

文件存在,但是当试图打开文件描述符时,出现异常:java.io.FileNotFoundException:打开失败:EACCES(权限被拒绝).

The file exists but when trying to open the file descriptor, an exception arises: java.io.FileNotFoundException: open failed: EACCES (Permission denied).

我阅读了 Android Q 存储中的更改,但无法弄清楚如何在没有用户交互的情况下读取文件.

I read the changes made in Android Q storage, but could not figure out how can I just read the file without having user interaction.

谢谢!

经过数小时试图弄清楚到底发生了什么事情后,我设法找到了解决方案.

After too many hours of trying to figure out what the hell is going on, I managed to find a solution.

我添加到清单中:

android:requestLegacyExternalStorage="true"

直接从 Android Studio 重建和重新安装时,构建系统或 android 运行时不会在清单中注册更改,并且对 requestLegacyExternalStorage 的请求不会注册.

When rebuilding and reinstalling directly from Android Studio, the build system or android runtime does not register a change in the manifest, and the request for requestLegacyExternalStorage does not register.

我通过完全卸载应用程序来修复它:adb uninstall com.example.app 并从 android studio 再次安装它.

I fixed it by completely uninstalling the app: adb uninstall com.example.app and installing it again from android studio.