androiddownloaddownload-manager

Set custom folder Android Download Manager


I've a question about Download Manager. I'm going to download a file from a site. When I set the default directory for download (Environment.DIRECTORY_DOWNLOAD) all works fine and my download is started. But if I try to change the directory, my app doesn't download the file. In particular, I want my file to go into a folder inside a Download, for example /storage/sdcard/Download/myFolder. How can I fix that?

File mydownload = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ "/myFolder");

if (!mydownload.exists()){
    mydownload.mkdir();
}

String url = sUrl[0];
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}

request.setDestinationInExternalPublicDir(mydownload.getAbsolutePath(),"Myfile.extension");


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

Solution

  • check below code: its save file in "sdcard/dhaval_files/". just replace your folder name and give permission write_external_storage in android manifest file.

    public void file_download(String uRl) {
            File direct = new File(Environment.getExternalStorageDirectory()
                    + "/dhaval_files");
    
            if (!direct.exists()) {
                direct.mkdirs();
            }
    
            DownloadManager mgr = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
    
            Uri downloadUri = Uri.parse(uRl);
            DownloadManager.Request request = new DownloadManager.Request(
                    downloadUri);
    
            request.setAllowedNetworkTypes(
                    DownloadManager.Request.NETWORK_WIFI
                            | DownloadManager.Request.NETWORK_MOBILE)
                    .setAllowedOverRoaming(false).setTitle("Demo")
                    .setDescription("Something useful. No, really.")
                    .setDestinationInExternalPublicDir("/dhaval_files", "test.jpg");
    
            mgr.enqueue(request);
    
        }