使用Android DownloadManager下载文件到外部存储在三星Galaxy S9、S9+上的Android 9(Pie)会失败。
对于安装有Android 8的三星设备或其他安装有Android 9的设备(例如Pixel 2),下载工作正常。
我已经在清单文件中添加了以下权限:
"android.permission.WRITE_EXTERNAL_STORAGE",
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.INTERNET"
我还在运行时请求了READ/WRITE_EXTERNAL_STORAGE权限。
文件路径为:
/storage/4295-DDD5/Android/data/com.example.myapplication/files/filename.file
并且此文件路径存在,我是使用AndroidStudio的设备文件资源管理器创建的。
创建下载的方法:
public void downloadFile(String url, String filePath) {
DownloadManager mDownloadManager =
(DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new
DownloadManager.Request(Uri.parse(url));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE |
DownloadManager.Request.NETWORK_WIFI);
request.setVisibleInDownloadsUi(true);
request.setDestinationUri(Uri.parse("file://" + filePath));
mDownloadManager.enqueue(request);
}
预期结果是从URL下载指定文件到filePath,但我在日志中得到以下错误:D/DownloadManager: [8616] Starting com.example.myapplication
W/DownloadManager: [8616] Stop requested with status FILE_ERROR: Failed to generate filename: java.io.IOException: Permission denied
D/DownloadManager: [8616] Finished with status WAITING_TO_RETRY
V/DownloadManager: MIME Type = application/octet-stream
I/DownloadManager: Download 8616 finished with status WAITING_TO_RETRY
I/DownloadManager: Notification Clear Download 1:com.example.myapplication