How to use the DownloadManager in Android?

To download files in the background and manage download tasks, you can utilize the system service called DownloadManager in Android. Follow the steps below to use DownloadManager for file downloads:

  1. Obtain an instance of DownloadManager:
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
  1. Create a DownloadManager.Request object and configure download parameters.
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://example.com/file.jpg"));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "file.jpg");
request.setTitle("File Download");
request.setDescription("Downloading file...");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
  1. Submit the download request to DownloadManager and obtain the ID of the download task.
long downloadId = downloadManager.enqueue(request);
  1. You can check the status and progress of a download task by using the Task ID to search for it.
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
    int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
    int progress = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
    int total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
}
  1. You can cancel the download task when needed.
downloadManager.remove(downloadId);

It is important to note that in order to use DownloadManager for file downloads, you need to add the appropriate permissions to the AndroidManifest.xml file.

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

The above are the basic steps for downloading files using DownloadManager, which allows for easy downloading of files and the management of download tasks’ status and progress in the background.

Leave a Reply 0

Your email address will not be published. Required fields are marked *