Using Download Manager in Android
Introduction
In Android, the Download Manager is a system service that handles long-running HTTP
downloads in the background. It is a built-in service that manages downloads, including file
saving, pausing, and resuming downloads while providing notifications for progress.
Why Use DownloadManager?
1. Efficient Handling of Long Downloads: It performs downloads in the background,
ensuring that the main UI thread is not blocked.
2. Automatic Pause and Resume: If a download is interrupted, it can resume from where it
left off.
3. Status Notifications: Provides built-in notifications showing download progress.
4. Optimized for Battery and Network Usage: Manages network requests efficiently.
Step-by-Step Implementation
Step 1: Add Required Permissions
In your `AndroidManifest.xml`, add the following permissions to allow internet access and
file writing:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Step 2: Define the Layout in `activity_main.xml`
In the `activity_main.xml`, add a `Button` that will trigger the download when clicked:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<Button
android:id="@+id/download_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Download File" />
</LinearLayout>
Step 3: Add Logic in `MainActivity.java`
In `MainActivity.java`, set up the button's `OnClickListener` to start the download using the
`DownloadManager`.
MainActivity.java Code
import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
Button downloadButton;
DownloadManager downloadManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downloadButton = findViewById(R.id.download_button);
downloadManager = (DownloadManager)
getSystemService(Context.DOWNLOAD_SERVICE);
downloadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// URL to the file you want to download
Uri fileUri = Uri.parse("https://www.example.com/sample.pdf");
// Create the download request
DownloadManager.Request request = new DownloadManager.Request(fileUri);
request.setTitle("Downloading File");
request.setDescription("Downloading the file from the internet…”);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,”sampl
e.pdf”);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
// Start the download
downloadManager.enqueue(request);
}
});
}
}
Step 4: Handle Download Completion
To monitor the completion of the download, register a **BroadcastReceiver** to listen for
the download status:
DownloadReceiver.java
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.widget.Toast;
public class DownloadReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
long downloadID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -
1);
DownloadManager downloadManager = (DownloadManager)
context.getSystemService(Context.DOWNLOAD_SERVICE);
Cursor cursor = downloadManager.query(new
DownloadManager.Query().setFilterById(downloadID));
if (cursor.moveToFirst()) {
int status =
cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
Toast.makeText(context, "Download Complete", Toast.LENGTH_SHORT).show();
} else if (status == DownloadManager.STATUS_FAILED) {
Toast.makeText(context, "Download Failed", Toast.LENGTH_SHORT).show();
}
}
cursor.close();
}
}
Step 5: Register Receiver in `MainActivity.java`
In your `MainActivity.java`, register the receiver dynamically to listen for download
completion:
@Override
protected void onResume() {
super.onResume();
registerReceiver(new DownloadReceiver(), new
IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(new DownloadReceiver());
}
Best Practices & Tips
1. Use DownloadManager for Large Files: It's designed to handle large downloads and
background tasks without blocking the UI thread.
2. Handle Download Failures: Ensure to implement error handling to track the status of
downloads, especially for network issues.
3. Use `setDestinationInExternalPublicDir()`: This method saves files in the public storage,
so they can be accessed by other apps or users.
4. Check Network Connection: Always check the device’s network status before starting a
download, and notify users of connectivity issues.