Android DownloadManager Listen to Download Complete and Cancel event/action (Java)

Is download complete or cancelled?

Create a BroadcastReceiver to listen to DownloadManager.ACTION_DOWNLOAD_COMPLETE intent.

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.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.