我有一台Galaxy S4手机,我的问题是我无法使用DownloadManager将文件下载到SD卡上。在模拟存储中它可以正常工作,但是对于真实的SD卡却会出现以下错误:
java.lang.SecurityException: Destination must be on external storage: file:///mnt/extSdCard/Android/data/net.myApp/files/exercises/exec.mp4
这是我的代码:
DownloadManager dwlManager=(DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request dwlmRequest=new DownloadManager.Request(Uri.parse("http://cdn..."));
File destination = new File("/mnt/extSdCard/Android/data/net.myApp/files/exercises/exec.mp4");
dwlmRequest.setDestinationUri(Uri.fromFile(destination));
dwlManager.enqueue(dwlmRequest); //<--- Here comes the error.
如果我将目标设置为:
File destination = new File(getExternalFilesDir(null), "exec.mp4");
代码工作得很好,因为目标地址位于模拟存储中。 此外,我也可以向SD卡创建文件,例如:
File f = new File("/mnt/extSdCard/Android/data/net.myApp/files/exercises/exec.mp4");
f.createNewFile();
它能够工作,但我无法使用下载管理器来下载到那个路径。
请帮忙。 我需要能够将文件下载到那个路径。
DownloadManager
会抛出一个特定的SecurityException
。如果你阅读DownloadProvider
源代码,你会发现checkFileUriDestination()
抛出这个异常来“检查为DESTINATION_FILE_URI提供的文件URI是否有效”。因此,它不受支持。DownloadManager
(或者更准确地说,DownloadProvider
)是一个普通的应用程序,除非以超级用户权限运行,否则没有任何应用程序有权写入任意路径。 - CommonsWare