Create a BroadcastReceiver
to listen to DownloadManager.ACTION_DOWNLOAD_COMPLETE
intent.
- Register the receiver only once, before any download take place
- Download is identified by
Download ID
, when you call downloadManager.enqueue(request)
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);DownloadReceiver downloadReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); if (downloadId == -1) return; // query download status 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){ // download is successful String uri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); File file = new File(Uri.parse(uri).getPath()); } else { // download is assumed cancelled } } else { // download is assumed cancelled } }};registerReceiver(downloadReceiver, filter);
Unregister the download receiver
if (downloadReceiver != null) { unregisterReceiver(downloadReceiver);}
NOTE: If you want to register a global Brodcast Receiver
, you need to create a DownloadBroadcastReceiver extends BroadcastReceiver
class and declear the following in AndroidManifest.xml
. Don't need to call registerReceiver
.
<receiver android:name=".DownloadBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
</intent-filter>
</receiver>
NOTE: I didn't the global Brodcast Receiver
method.