Download Manager in Android to download Files

The Download Manager was introduced in Android 2.3 (API level 9) as a Service to optimize the handling of long-running downloads. The Download Manager handles the HTTP connection and monitors connectivity changes and system reboots to ensure each download completes successfully

To access the Download Manager, request the DOWNLOAD_SERVICE using the getSystemService method, as follows:

String serviceString = Context.DOWNLOAD_SERVICE;
DownloadManager downloadManager;
downloadManager = (DownloadManager)getSystemService(serviceString);

Downloading Files

String serviceString = Context.DOWNLOAD_SERVICE;
DownloadManager downloadManager;
downloadManager = (DownloadManager)getSystemService(serviceString);
Uri uri = Uri.parse(“http://developer.android.com/shareables/icon_templates-v4.0.zip”);
DownloadManager.Request request = new Request(uri);
long reference = downloadManager.enqueue(request);

You can use the returned reference value to perform future actions or queries on the download, including checking its status or canceling it.

You can add an HTTP header to your request, or override the mime type returned by the server, by calling addRequestHeader and setMimeType, respectively, on your Request object

You can also specify the connectivity conditions under which to execute the download. The setAllowedNetworkTypes method enables you to restrict downloads to either Wi-Fi or mobile networks, whereas the setAllowedOverRoaming method predictably enables you to prevent downloads while the phone is roaming

The following snippet shows how to ensure a large fi le is downloaded only when connected to Wi-Fi:

request.setAllowedNetworkTypes(Request.NETWORK_WIFI);

Android API level 11 introduced the getRecommendedMaxBytesOverMobile convenience method, which is useful to determine if you should restrict a download to Wi-Fi by returning a recommended maximum number of bytes to transfer over a mobile data connection.

After calling enqueue, the download begins as soon as connectivity is available and the Download Manager is free.

To receive a notification when the download is completed, register a Receiver to receive an ACTION_ DOWNLOAD_COMPLETE broadcast. It will include an EXTRA_DOWNLOAD_ID extra that contains the reference ID of the download that has completed

Monitoring downloads for completion

IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
 
BroadcastReceiver receiver = new BroadcastReceiver() {
 @Override
 public void onReceive(Context context, Intent intent) {
 long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
 if (myDownloadReference == reference) {
 // Do something with downloaded file.
 }
 }
};
 
registerReceiver(receiver, filter);

Responding to download notification clicks

IntentFilter filter = new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED);
BroadcastReceiver receiver = new BroadcastReceiver() {
 @Override
 public void onReceive(Context context, Intent intent) {
 String extraID = DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS;
 long[] references = intent.getLongArrayExtra(extraID);
 for (long reference : references)
 if (reference == myDownloadReference) {
 // Do something with downloading file.
 }
 }
};
registerReceiver(receiver, filter);

Customizing Download Manager Notifications

By default, ongoing Notifications will be displayed for each download managed by the Download Manager. Each Notification will show the current download progress and the filename

Customizing Download Manager Notifications

The Download Manager enables you to customize the Notification displayed for each download request, including hiding it completely. The following snippet shows how to use the setTitle and setDescription methods to customize the text displayed in the fi le download Notification

request.setTitle(“Earthquakes”);
request.setDescription(“Earthquake XML”);
Customizing Download Manager Notifications

The setNotificationVisibility method lets you control when, and if, a Notification should be displayed for your request using one of the following flags:

Request.VISIBILITY_VISIBLE — An ongoing Notification will be visible for the duration that the download is in progress. It will be removed when the download is complete. This is the default option

Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED — An ongoing Notification will be displayed during the download and will continue to be displayed (until selected or dismissed) once the download has completed.

Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION — The notifi cation will be displayed only after the download is complete.

Request.VISIBILITY_HIDDEN — No Notification will be displayed for this download. In order to set this fl ag, your application must have the DOWNLOAD_WITHOUT_NOTIFICATION uses-permission specified in its manifest.

Specifying a Download Location

By default, all Download Manager downloads are saved to the shared download cache using system generated filenames. Each Request object can specify a download location, though all downloads

must be stored somewhere on external storage and the calling application must have the WRITE_ EXTERNAL_STORAGE uses-permission in its manifest:

<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”/>

The following code snippet shows how to specify an arbitrary path on external storage:

request.setDestinationUri(Uri.fromFile(f));

If the downloaded fi le is to your application, you may want to place it in your application’s external storage folder. Note that access control is not applied to this folder, and other applications will be able to access it. If your application is uninstalled, fi les stored in these folders will also be removed.

The following snippet specifies storing a fi le in your application’s external downloads folder:

request.setDestinationInExternalFilesDir(this, 
 Environment.DIRECTORY_DOWNLOADS, “Bugdroid.png”);

For fi les that can or should be shared with other applications — particularly those you want to scan with the Media Scanner — you can specify a folder within the public folder on the external storage. The following snippet requests a fi le be stored in the public music folder:

request.setDestinationInExternalPublicDir(Environment.DIRECTORY_MUSIC,
 “Android_Rock.mp3”);

It’s important to note that by default fi les downloaded by the Download Manager are not scanned by Media Scanner, so they might not appear in apps such as Gallery and Music Player.

To make downloaded fi les scannable, call allowScaningByMediaScanner on the Request object.

If you want your fi les to be visible and manageable by the system’s Downloads app, you need to call setVisibleInDownloadsUi, passing in true.

Leave a Comment