How to download a file in Android

Today in this post, I am going to share the code that I use in my android applications to support downloading of file. There are many ways you can use to download a file. For example you can use Async task and read the file stream to save it in device storage, you could also use a Service to download the file. But in my example I will show you the code that uses DownloadManager class.


The code sample using DownloadManager class is as follows:
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void downloadFile(Context context, String file, String title, String subtitle) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(file));
request.setTitle(title);
request.setDescription(subtitle);
//request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI); //to allow download while using WIFI only
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
String nameOfFile = URLUtil.guessFileName(file, null, MimeTypeMap.getFileExtensionFromUrl(file));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, nameOfFile);
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}

Now to use this function
downloadFile(context, "http://i.imgur.com/DvpvklR.png", 
"File download",
"File is being downloaded...");
Hope this helps you.

Comments

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete

Post a Comment

Popular posts from this blog

Automate file upload in Selenium IDE

How To Install and Configure Nextcloud

Google translate adds Nepali Language Conversion