Free Android app covering all aspects of addiction, including prevention and treatment

Using the DownloadManager to manage your downloads

  • Written by  Clive

Let someone else manage your downloads!

The DownloadManager

Android DownloadManager tutorial for managing downloadsThe download manager was introduced in Android 2.3 (API level 9).

It’s a System Service that optimises the handling of long-running downloads in the background.

The download manager handles HTTP connections, monitors connectivity changes, reboots, and ensures each download completes successfully

Its good practice to use the download manager for most downloads, especially if the download continues between user sessions or if success is important.

Our Tutorial app

Running our app displays a screen with two buttons.

The top button checks for a network connection. Pressing it displays a Toast message showing the network status.

Have a look at the project code. Maybe you can use it in your future apps to check for a network connection.

The bottom button starts managing the download of an image file.

Two broadcast receivers are registered in the activity’s onResume() method.

One receives a broadcast when the download has completed. It checks the status of the download and if successful, starts an activity where the downloaded image is displayed.

The other receives a broadcast when the download notification is clicked.

DownloadManager tutorial app screenshot

Click the Start Download button to download an image. On success, it is displayed in another activity

Check if we have a network connection

I don't do this but you can if you want to. You can use the Connectivity Manager to check whether there is a current network connection. Then, if you choose, only if there is one will the download proceed.

Have a look at the project code to see how it’s done.

The download manager will keep trying to download the file until there is a connection.

You’ll need to add these permissions to the AndroidManifest.xml file:

Network and Internet permission

You’ll need these permissions to access the network and query the network status

Getting the download manager

The preparation

We create a number of fields in our MainActivity activity:

DownloadManager fields

Fields used by our DownloadManager application

Note the following:

  • downloadManager – our download manager. The download manager is a system service handling HTTP downloads. It takes care of all aspects of the download, handling HTTP connections, connectivity changes, system reboots, and ensures each download completes successfully. The download takes place in the background
  • downloadFileUrl – the URL of the file that we want to download
  • myDownloadReference – a unique ID that we will use to identify a specific download request
  • receiverDownloadComplete – a broadcast receiver that we will register to receive a broadcast on completion of the download
  • receiverNotificationClicked – a notification displays for each download. This is a broadcast receiver that we will register to receive a broadcast when these notifications are clicked

Getting an instance of a DownloadManager

We get an instance of DownloadManager with this code snippet:

Get DownloadManager instance

Create our Download Manager

It’s all in the button

I’ve put all the code that starts the download within our buttonDownload’s onClick() method:

Here’s the code:

Create a DownloadManager request object

Create a download request

Note the following:

  • uri – we create a Uri given the Url string, downloadFileUrl. This is the Uri of the file that we want to download
  • request – our Request object. We’ll build it to our specifications and then put the request in the download queue. The download manager will take care of the rest

The notification

By default, an ongoing notification will display as the file downloads. The notification automatically cancels itself when the download has finished.

notification

The top notification displays when there is no connection. The bottom one displays as the file downloads. By default, it is cancelled on completion

You can customize the notification.

Here’s how I used the DownloadManager to set the title and description of the notification:

Customise the notification

Customise the notification

There are other settings:

  • to hide the notification
  • to only show it while the download is in progress
  • to show it while in progress and after completion
  • to only show after completion

Where will the file be saved?

The download manager uses system generated file names and saves all files in the shared download cache.

You can also choose where to save the file. But, you can only save it in the external storage.

You’ll need to add permission for this in the AndroidManifest.xml file:

Get permission to write to the external storage

Get permission to write to the external storage

Here’s the code for setting the destination for the saved file:

Set the destination for the downloaded file

Set the destination for the downloaded file

Note the following:

  • setDestinationInExternalFilesDir() – saves the file in the apps external downloads folder. The parameters are:
    • context
    • the directory type
    • the filename
  • setDestinationExternalPublicDir() – saves the file in the public external storage folder. The parameters are:
    • the directory type
    • the filename
  • setDestinationUri(uri) – used to save the file anywhere else in the external storage space. The parameter is:
    • uri – path to where you want the file saved

Note that files downloaded by the download manager, are by default, not scanned by the Media Scanner. So, downloaded pictures won’t be included in the Gallery app and music files won’t be included in the Music Player.

As of API level 11, you can set the downloads to be scanned by using the allowScanningByMediaScanner() method.

Fine tune your download

Here are some more settings for the requested download:

Additional download settings

Additional settings for the downloaded file

Note the following:

  • setVisibleInDownloadsUi() – sets whether the downloaded file should be displayed in the system’s Download UI. It’s true by default
  • setAllowedNetworkTypes() – restricts the type of network connection to use for this download. Default is all networks

Finally, we put the download request into the queue:

enqueue the download request

The download begins once there is a network connection and the Download Manager is available

The Broadcast Receivers

We register two broadcast receivers. One receives a broadcast when the download is complete and the other receives a broadcast when the user clicks on the download notification while the download is in progress.

Both are registered in the activity’s onResume() method.

The notifications broadcast receiver

The notifications broadcast receiver

The notification broadcast receiver

Note the following:

  • filter – filters broadcasts sent when the download notification is clicked while the file is downloading
  • receiverNotificationClicked – our new notifications broadcast receiver
  • extraId – the key we’ll use to get an array of ID’s
  • references – we get an array of long values out of the broadcast intent. These are id’s for each download. Each download has an ID and each time that download’s notification is clicked, its id is added to the array
  • for loop – we loop through the array of download ID’s
  • If statement – we check to see if any of the id’s match our download id, myDownloadReference. If there is a match then we can do something with the downloaded file if we wish
  • registerReceiver() – we register the receiver, passing two parameters:
    • our broadcast receiver
    • the filter

The download broadcast receiver

The download complete broadcast receiver

The download complete broadcast receiver

Note the following:

  • filter –filters broadcasts sent when the download is complete
  • receiverDownloadComplete - our new download complete broadcast receiver
  • reference – we get the reference ID for this particular download out of the broadcast intent
  • if statement – we check if this reference ID matches our reference, myDownloadReference
  • query – if there is a match then we perform a query on the download manager
  • setFilterById() – we filter the query for information relevant to our reference ID
  • cursor – the result of the query is returned in a cursor

Next, we position the indicator to the first row of the cursor:

Getting the values out of the cursor

Get the data out of the cursor

Note the following:

  • there are a number of columns containing data. Each has an index
  • columnIndex – we get the index for the status column
  • status – we get the value in the status column
  • fileNameIndex – we get the index for the filename column
  • savedFilePath – we get the saved file’s path from the filename column
  • columnReason – we get the index for the reason column
  • reason – we get the details of the status out of the reason column. This provides more information about the status of the download

We now use a switch statement to evaluate status. The status column can have one of 5 values:

  • pending – 1
  • running – 2
  • paused - 4
  • success – 8
  • failed – 16

Here’s the code:

The download switch statement

The switch statement

Note the following:

  • success – we create an intent, put the uri of the saved file in it and then start the DisplayActivity activity to display the image
  • the remaining status’s – we display an appropriate Toast message, including a reason where applicable

Finally, we close the cursor and register the receiver.

Unregister the receivers

We unregister the receivers in the activity’s onPause() method:

Unregister the receivers in onPause

Unregister the receivers in the onPause() method

The display activity

The DisplayActivity Activity starts once the download has completed successfully.

It receives the uri of the saved image and decodes this to get a bitmap. The bitmap is then displayed in the image view.

Here’s the code:

The image is displayed in the DisplayActivity

The image is displayed in the DisplayActivity activity

Cancelling downloads

You can cancel a download at any time using the remove(ref1, ref2,ref3) method.

Pass the method the reference ID’s of downloads that you want cancelled.

  • Running downloads will be stopped and removed from the download manager
  • Any downloaded files (complete or partial) will be deleted

The remove() method will return the number of downloads removed.

I hope that you have found this tutorial helpful.

Please consider subscribing to our notification email. We’ll send you one email on Friday with links to our latest tutorials. That way you won’t miss out. If we didn’t publish any then we won’t send any email. No spam. 

This tutorial was created using Android Studio. You can download the project files here Download icon

Are you using Eclipse or another IDE? Here's how you can use this project's Android Studio files.