Downloading files using Download Manager in Android

Download Manager
Download Manager is a system service which allows to handle long-running HTTP downloads in the background and notify the triggering application via a broadcast receiver once the download is finished. It was introduced in Android 2.3. (API 9).
Download manager helps use reduce the burden of writing our own download service with all those error handling. In this tutorial we will see how to create a download manager to download a file in background and notify the application once the file is downloaded.
Source code is provided at the end of this article. You may download and check out yourself.
First, Add the Download Manager in your onCreate().
1 2 3 4 5 |
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); |
Single File Download
For downloading a single file, follow the below mentioned code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
btnSingle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Download_Uri = Uri.parse("http://www.gadgetsaint.com/wp-content/uploads/2016/11/cropped-web_hi_res_512.png"); DownloadManager.Request request = new DownloadManager.Request(Download_Uri); request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE); request.setAllowedOverRoaming(false); request.setTitle("GadgetSaint Downloading " + "Sample" + ".png"); request.setDescription("Downloading " + "Sample" + ".png"); request.setVisibleInDownloadsUi(true); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/GadgetSaint/" + "/" + "Sample" + ".png"); refid = downloadManager.enqueue(request); } }); |
In the above code, We are passing a request to the Download Manager with the download file URL, Title and Description to be shown in notification bar etc. We can also specify whether the download should happen over wifi or cellular or both.
Multiple file Downloads
Downloading multiple files is easy. just need to add the above request in a loop. The download requests will be added into the queue.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
for(int i = 0; i < 2; i++) { Download_Uri = Uri.parse("http://www.gadgetsaint.com/wp-content/uploads/2016/11/cropped-web_hi_res_512.png"); DownloadManager.Request request = new DownloadManager.Request(Download_Uri); request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE); request.setAllowedOverRoaming(false); request.setTitle("GadgetSaint Downloading " + "Sample_" + i + ".png"); request.setDescription("Downloading " + "Sample_" + i + ".png"); request.setVisibleInDownloadsUi(true); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/GadgetSaint/" + "/" + "Sample_" + i + ".png"); refid = downloadManager.enqueue(request); } |
In the above code sample, I am using a single download url in the loop. You may use multiple urls depending on your requirements by adding it in a list and iterating it.
Listening to Download Complete
You may listen when a download is completed and perform some actions like showing a download completed notification. In order to do that you need to keep a track of the refid that we get while enqueuing the download requests. After every enqueue add the refid into an Array list as shown below.
Create an Arraylist of type long.
1 2 3 4 5 |
ArrayList<Long> list = new ArrayList<>(); |
And add the refid whenever you request the download manager
1 2 3 4 5 6 7 8 |
refid = downloadManager.enqueue(request); // add the refid into an arraylist list.add(refid); |
Now create a Broadcast Receiver to listen to the “Download Completed” Broadcasts. This will be triggered everytime a download is completed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
BroadcastReceiver onComplete = new BroadcastReceiver() { public void onReceive(Context ctxt, Intent intent) { // get the refid from the download manager long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); // remove it from our list list.remove(referenceId); // if list is empty means all downloads completed if (list.isEmpty()) { // show a notification Log.e("INSIDE", "" + referenceId); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("GadgetSaint") .setContentText("All Download completed"); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(455, mBuilder.build()); } } }; |
In OnCreate, Register the receiver like below
1 2 3 4 5 6 |
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); |
In onDestroy, unRegister the receiver,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(onComplete); } |
Permissions
Don’t forget to add the following permissions in the Manifest file. If you are using Android 6 or above, Handle the Permissions.
1 2 3 4 5 6 7 |
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> |
For more clarifications, Checkout the source code from Github below.
Preview
SourceCode
Download the source code from Github
Let me know your Suggestions / Queries in comments.
Hello,
Thanks for this post. But I want to download files in my own Client. Don’t use Mobile’s download Client or manager. Is it possible? Please help me.
Yes its possible. https://stackoverflow.com/questions/1714761/download-a-file-programmatically-on-android
thank you for this wonderful tutorial.Please help me i want to show multiple progress bars with percentage in listview for Multiple file Downloads.If i close the app when i return i need updated progress bars with percentage.I know that this service goes on even app is closed.
Thanking you for this wonderful tutorial.Please help me i want to show multiple progress bars with percentage in listview for Multiple file Downloads.If i close the app when i return i need updated progress bars with percentage.I know that this service goes on even app is closed.
Many funny amigop, I implemented it and it is super. But I have a query, at the end of the download, in the notifications, by giving the touch to want to open, it does not open. Is there a call I have to make to the notification? I’m sorry for my English
Simple tutorial. Good One. Thanks. It will be great if you can add download queue as well for a list of files.
can i place download links into gridview on android ?
It helped.
Thanks!!!
It helped! Thanks mate 🙂
Thanks for this tutorial But I just want to download multiple videos with file path of that particular files to show in recyclerview help me if you can
how i get file path
гидра официальный – гидра зеркало, гидра онион
https://pizdeishn.com/devstven/107-moy-pervyy-seks.html – Жесткие порно истории, Реальные порно рассказы
Thnaks …it was helpful solution
Thanks*
Hello and welcome to my blog . I’m Kyran.
I have always dreamed of being a book writer but never dreamed I’d make a career of it. In college, though, I aided a fellow student who needed help. She could not stop telling me how well I had done. Word got around and someone asked me for to write their paper just a week later. This time they would pay me for my work.
During the summer, I started doing research papers for students at the local college. It helped me have fun that summer and even funded some of my college tuition. Today, I still offer my writing services to students.
Academic Writer – Kyran Mckinney – Killer Papers Company
my company hydra 2020
helpful hints
vulkan vegas erfahrung
Hi everyone , I’m Eduard Jaramillo.
Welcome to my about page. I started writing in middle school after a creative writing assignment for my English teacher. I did creative writing for several months before I thought about doing something else.
I had always loved doing research assignments because I’m passionate about learning. When you combine writing talent with a love of learning, academic writing only makes sense as a job.
I’m passionate about aiding the students of the future in their school career. When they don’t have time for their paper , I am there to help.
Eduard Jaramillo – Writing Expert – Tips to make remote work effective. Corp
Good day and welcome to my webpage. I’m Leonard Rossi.
I have always dreamed of being a writer but never dreamed I’d make a career of it. In college, though, I helped a fellow student who needed help. She could not stop complimenting me . Word got around and someone asked me for to write their paper just a week later. This time they would pay me for my work.
During the summer, I started doing research papers for students at the local college. It helped me have fun that summer and even funded some of my college tuition. Today, I still offer my writing services to students.
Professional Writer – Leonard Rossi – http://www.asadeaguia.net Corp
(palimpsests). In the XIII-XV centuries in
Since manuscripts are subject to deterioration
Hello All
Thanks for checking out my academic writing page . My name is Nannie.
I have worked a long time in this niche. My aptitude for writing started at a young age. I wrote journaled as a child and eventually went on to work with my school newspaper.
This early tryst into reporting eventually led me to academic writing. There is plenty of work for skilled writers. I specialize in research papers , but have the skills to do all types of academic writing.
Email me for more information about rates and a price quote. I’m looking forward to helping you.
Academic Writer – Nannie – http://www.queronaao.com Corps
Hello, it’s Reema here!
I work as an academic writer and have created this content with the intent of changing your life for the better. I started honing my writing abilities in my school years. I learned that my fellow students needed writing help—and they were willing to pay for it. The money was enough to help pay my tuition for my first semester of college.
Ever since college, I have continued to work as a professional writer. I was hired by a writing company based in the United Kingdom. Since then, the essays that I have created have been sold around Europe and the United States.
In my line of work, I have become accustomed to hearing, “Reema, can you help me meet my writing assignment deadline?” I know that I can provide this service.
Professional Writer – Reema Bright – http://www.leadershipeducationnelenhaiti.comTeam
and 12 thousand Georgian manuscripts
new texts were rewritten
Manuscript is a collective name for texts
The most common form
and 12 thousand Georgian manuscripts
Have you heard that notes like these that come through your website’s contact page are in fact an effective method to get more visitors and sales for your website? How exactly is this done? Easy, we put together an ad like the one you’re reading right now for your business and we mass post it to lots of contact forms on any kind of website you want. Do these types of ads work? You’re living proof that they do since you’re reading this message right now What’s more, this doesn’t cost more than $3 a day! Want more info? shoot us a quick email to: UlisesDonaldsoni4472@gmail.com