Courtesy: Android DonwnloadManager Example
The accepted answer is not completely correct. Receiving ACTION_DOWNLOAD_COMPLETE broadcast doesnt mean your download is complete. Note that ACTION_DOWNLOAD_COMPLETE is broadcasted by DownloadManager when any download is completed. It doesnt necessarily mean it is the same download which you are waiting for
Solution is to save the download id returned by enqueue() when starting the download. This long download id is unique across the system and can be used to check the download status
DownloadManager downloadManager= (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
long downloadID = downloadManager.enqueue(request);// enqueue puts the download request in the queue.
You can be notified when your download is complete by following three steps
Create a BroadcastReceiver as shown in snippet below.Inside the receiver we just check if the received broadcast is for our download by matching the received download id with our enqueued download.
private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//Fetching the download id received with the broadcast
long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
//Checking if the received broadcast is for our enqueued download by matching download id
if (downloadID == id) {
Toast.makeText(MainActivity.this, "Download Completed", Toast.LENGTH_SHORT).show();
}
}
};
Once the BroadcastReceiver is created you can register for ACTION_DOWNLOAD_COMPLETE in the onCreate method of your activity.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(onDownloadComplete,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
It is also important that you unregister the BroadcastReceiver in onDestroy. This ensures you only listen for this broadcast as long as the activity is active
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(onDownloadComplete);
}
I urge your to read the complete example here