Reputation: 1647
There are some similar questions have been asked, but mine is a bit different, i have the following code to do a download on my application:
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);
This works fine without complaining on at least Samsung S4, Nexus 4, Nexus 7, however i recently found out that on some devices it fails to create the directory with the error:
so now i am checking for the directory and creating if it doesn't exist with
File downloadDir = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
+ File.separator + getString(R.string.app_name));
if (!downloadDir.exists()){
boolean mkdir = downloadDir.mkdir();
}
My question is why DownloadManager behaves different is this an Android version or vendor issue and what is the expected behaviour, since the documentation for getExternalStoragePublicDirectory
states that it might throw an IllegalStateException: IllegalStateException If the external storage directory cannot be found or created.
I assumed it should try to create the directory in that case there should be no reason or need for me to use the mkdir
function but it isn't so
Upvotes: 3
Views: 467
Reputation: 7226
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();
}
}
Upvotes: 3