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:
Now to use this function
The code sample using DownloadManager class is as follows:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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
Hope this helps you.downloadFile(context, "http://i.imgur.com/DvpvklR.png", "File download", "File is being downloaded...");
This comment has been removed by a blog administrator.
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDelete