DownloadManager无法使用Pie下载到三星的外部存储上

Oag*_*gar 10 android android-download-manager android-external-storage samsung-galaxy android-9.0-pie

在Android 9(Pie)上的Samsung Galaxy S9和S9 +上,使用Android DownloadManager将文件下载到外部存储失败。

下载适用于具有Android 8的三星设备或具有Android 9(例如Pixel 2)的其他设备

我已将以下权限添加到清单中:

 "android.permission.WRITE_EXTERNAL_STORAGE", 
 "android.permission.READ_EXTERNAL_STORAGE",
 "android.permission.INTERNET"
Run Code Online (Sandbox Code Playgroud)

我还已在运行时请求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);
}
Run Code Online (Sandbox Code Playgroud)

预期的结果是将指定文件从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
Run Code Online (Sandbox Code Playgroud)

Ale*_*avo 0

Oagar,过去对我有帮助的是阅读https://commonsware.com/blog/archive.html上的全部 8 篇“外部存储之死”博客文章

我认为根本原因在于:

文件路径为: /storage/4295-DDD5/Android/data/com.example.myapplication/files/filename.file 并且此文件路径存在,我使用 AndroidStudio 的设备文件资源管理器创建了它

仅仅因为创建了此目录并看到它并不意味着您的应用程序能够写入其中。因此,请尝试在您确定可以写入文件的地方进行写入。

希望这会对您有所帮助。

  • 文件路径选择是通过以下方法“ContextCompat.getExternalFilesDirs(context, null);”完成的。该错误是 Android API 组件 DownloadManager 无法访问应用程序的“隔离存储沙箱”。如果我使用输入流: `InputStream in = new URL(fileUrl).openStream(); Files.copy(in, Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);` 一切正常,文件已下载到该位置。 (3认同)