Search code examples
javaandroidandroid-download-manager

Download Manager - setting file extension without hardcoding


I want to download a file which can be of any extension, using a url which does not contain the file type. Hardcoding the file type will not work here.

Uri downloadUrl = Uri.parse(link); 
DownloadManager.Request request = new DownloadManager.Request(downloadUrl);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(true);
request.setTitle(title);
request.setDescription(description); 
request.setVisibleInDownloadsUi(true);
request.setMimeType("application/pdf"); 
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, subDirectory);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager downloadManager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
if (downloadManager != null) {
    downloadManager.enqueue(request);
}

Solution

  • Try this:

    File file=new File(getExternalFilesDir(null),"Dummy");
    /*
    Create a DownloadManager.Request with all the information necessary to start the download
    */
    DownloadManager.Request request = 
        new DownloadManager.Request(Uri.parse("YOUR URL"))
           .setTitle("Dummy File")// Title of the Download Notification
           .setDescription("Downloading")// Description of the Download Notification
           .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)// Visibility of the download Notification
           .setDestinationUri(Uri.fromFile(file))// Uri of the destination file
           .setRequiresCharging(false)// Set if charging is required to begin the download
           .setAllowedOverMetered(true)// Set if download is allowed on Mobile network
           .setAllowedOverRoaming(true);// Set if download is allowed on roaming network
    

    then:

    DownloadManager downloadManager= 
        (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    
    // enqueue puts the download request in the queue.
    downloadID = downloadManager.enqueue(request);
    

    for complete example see the link.