我已经针对这个问题苦苦纠缠了很长时间...... 我正在更新一个应用程序,该应用程序使用DownloadManager执行简单任务,例如将文件下载到外部存储公共目录,即:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
在 Android api 19-28 上一切正常。问题出现在测试 API 29(Q/10)上。Android 实施了作用域存储并弃用了 getExternalStoragePublicDirectory... 因此,我需要找出一个兼容的解决方案来支持 APIs 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),但是我无法从保存下载文件的区域获取下载文件。我检查了文件是否存在,返回为假:
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)