Java – Use DownloadManager to download to a new folder on your phone’s storage

Use DownloadManager to download to a new folder on your phone’s storage… here is a solution to the problem.

Use DownloadManager to download to a new folder on your phone’s storage

I’m using the download manager to download files to a new folder on my phone’s storage. Here is the code I used:

DownloadManager.Request downloadSample = new DownloadManager.Request(Uri.parse(urlSample));
downloadSample.allowScanningByMediaScanner();
downloadSample.setDestinationInExternalPublicDir("/Samples/"+previewName, "sample.ttf");
downloadSample.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);    

DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(downloadSample);

This works fine on many devices I’ve tested, but some force the app to close and show the following error in the logs:

E/AndroidRuntime(29918): java.lang.IllegalStateException: Unable to create directory: /storage/sdcard0/Samples/Helvetica
E/AndroidRuntime(29918): at android.app.DownloadManager$Request.setDestinationInExternalPublicDir(DownloadManager.java:507)

Annoyingly, it works well on some devices but not at all on others. Does anyone know why this is happening?

Solution

The documentation for setDestinationInExternalPublicDir(String dirType, String subPath) says that dirType can only take specified values.

The dirType here can only be an android-defined directory, for example:

Environment.DIRECTORY_DOWNLOADS 

And so on

You can find all possible values for dirType at: http://developer.android.com/reference/android/os/Environment.html#getExternalStoragePublicDirectory(java.lang.String)

So the correct way to use this method is:

setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, subPath)

Also note that this will make the folder located in the Downloads folder on your phone’s storage. Download Manager does not allow you to create folders in the default directory where your phone is stored.

The

directory is created without an IllegalStateException.

Related Problems and Solutions