Search code examples
androidandroid-intentbroadcastreceiverdownload-manager

Set extras for DownloadManager's BroadcastReceiver


There's a way to put extras in DownloadManager's intent registered for actionDownloadManager.ACTION_DOWNLOAD_COMPLETE (e.g. receive a boolean value set as extra in the intent)?

This is how I create the request:

DownloadManager.Request req = new DownloadManager.Request(myuri);
// set request parameters
//req.set...
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
downloadManager.enqueue(req);
context.registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

And in my onComplete receiver:

private BroadcastReceiver onComplete = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        queryRequestParameters(context, intent);
    }
};

private void queryRequestParameters(Context context, Intent intent) {
    // get request bundle
    Bundle extras = intent.getExtras();
    DownloadManager.Query q = new DownloadManager.Query();
    q.setFilterById(extras.getLong(DownloadManager.EXTRA_DOWNLOAD_ID));
    Cursor c = ((DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE)).query(q);
    //get request parameters
    if (c.moveToFirst()) {
        int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
        if (status == DownloadManager.STATUS_SUCCESSFUL) {
            // find path in column local filename
            String path = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
        }
    }
}

With intent.getExtras() I can obtain only request parameters. I tried to send Broadcast to same receiver with different actions (one with ACTION_DOWNLOAD_COMPLETED, the other is custom), but I have to send a double broadcast so it will enter two times in the onReceive.


Solution

  • There's a way to put extras in DownloadManager's intent registered for actionDownloadManager.ACTION_DOWNLOAD_COMPLETE (e.g. receive a boolean value set as extra in the intent)?

    No. Use the ID you get back from enqueue() to store your desired boolean somewhere persistent (e.g., in a file), so you can read that value back in when you receive your broadcast.

    Also, with respect to your code snippet, bear in mind that your process may not be around by the time the download is completed. Your BroadcastReceiver registered via registerReceiver(), therefore, may never get triggered.