DownloadManager不适用于Android 10(Q)

问题描述 投票:0回答:1

我已经很长时间对这个问题不屑一顾了……我正在更新一个使用DownloadManger来执行简单任务的应用程序,例如将文件下载到外部存储公共目录,即:

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)

[Android api 19-28,一切正常。在API 29(Q / 10)上进行测试时会出现问题。 Android实现了范围存储,因此不赞成使用getExternalStoragePublicDirectory ...因此,我需要找出一种兼容的解决方案来支持API 19-29。我无法使用内部应用程序存储,因为DownloadManager会引发SecurityException。 Android的文档指出,我可以使用DownloadManager.Request setDestinationUri,对于Android Q,它甚至提到我可以使用Context.getExternalFilesDir(String)。但是,当我执行此操作时,该路径仍然是模拟路径:

/storage/emulated/0/Android/data/com.my.package.name/files/Download/myFile.xml

我从下载管理器收到一个回调,说明下载已完成(具有正确的ID),但是我无法从保存它的区域中获取下载。我检查文件是否存在,并返回false:

new File("/storage/emulated/0/Android/data/com.my.package.name/files/Download/myFile.xml").exists();

感谢您的任何帮助

添加上下文代码。因此,设置下载管理器

    private void startDownload() {
        IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        registerReceiver(downloadReceiver, filter);

        String remoteURL= getString(R.string.remote_url);

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(remoteUrl));
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setTitle(getString(R.string.download_title));
        request.setDescription(getString(R.string.download_description));
        request.setDestinationUri(Uri.fromFile(new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "myFile.xml")));

        DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        mainDownloadID= manager.enqueue(request);
    }

检查文件是否存在:

new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "myFile.xml").exists(); //this returns false in the onReceive (and download IDs match)
android download android-download-manager android-10.0 scoped-storage
1个回答
0
投票

尝试将其添加到清单文件中

© www.soinside.com 2019 - 2024. All rights reserved.