有一些类似的问题已被问到,但我的有点不同,我有以下代码在我的应用程序上下载:
DownloadManager.Request request = new DownloadManager.Request(uri)
.setTitle(fileInfo.getFileName())
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
getString(R.string.app_name) + File.separator + fileInfo.getFileName());
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
}
manager.enqueue(request);
这样可以正常工作而不会抱怨至少三星S4,Nexus 4,Nexus 7,但是我最近发现在某些设备上它无法创建带错误的目录:
所以现在我正在检查目录并创建它是否与
不存在File downloadDir = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
+ File.separator + getString(R.string.app_name));
if (!downloadDir.exists()){
boolean mkdir = downloadDir.mkdir();
}
我的问题是,为什么DownloadManager行为不同,这是Android版本或供应商问题以及预期的行为是什么,因为getExternalStoragePublicDirectory
的文档声明它可能会抛出IllegalStateException: IllegalStateException If the external storage directory cannot be found or created.
我认为它应该尝试创建目录,在这种情况下应该没有理由或者我需要使用mkdir
函数,但事实并非如此
答案 0 :(得分:1)
I had the same behavior on LG G3 without subdirectory creation:
W/DownloadManager: Aborting request for download 544: Failed to create target file /storage/emulated/0/Download/Sub Directory/IMG_20150422_160932.jpg
com.android.providers.downloads.StopRequestException: Failed to create target file /storage/emulated/0/Download/Sub Directory/IMG_20150422_160932.jpg
at com.android.providers.downloads.Helpers.getFullPath(Helpers.java:213)
at com.android.providers.downloads.Helpers.generateSaveFile(Helpers.java:166)
at com.android.providers.downloads.DownloadThread.processResponseHeaders(DownloadThread.java:2054)
at com.android.providers.downloads.DownloadThread.access$500(DownloadThread.java:130)
at com.android.providers.downloads.DownloadThread$ContentAnalyzer.init(DownloadThread.java:274)
at com.android.providers.downloads.DownloadThread.executeDownload(DownloadThread.java:922)
at com.android.providers.downloads.DownloadThread.runInternal(DownloadThread.java:784)
calling this method before helps:
private void createDirectoryIfNecessary() {
File downloadDir = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
+ File.separator + subdirectory);
if (!downloadDir.exists()){
downloadDir.mkdirs();
}
}