Search code examples
androidandroid-intentbroadcastreceiverandroid-manifest

Setup two broadcast receiver of same intent inside one activity


There are two download manager inside an activity, and I register two different broadcast receiver for the same intent.

The problem is , there are nothing like "request code" , and the two receiver seems overlapped, sometime trigger the first and sometime trigger the second.

mgr = (DownloadManager) ctx.getSystemService(Context.DOWNLOAD_SERVICE);
                        ctx.registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
                        mgr.enqueue(request);

mgr = (DownloadManager) ctx.getSystemService(Context.DOWNLOAD_SERVICE);
                        ctx.registerReceiver(onImgComplete , new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
                        mgr.enqueue(request);

    onComplete = new BroadcastReceiver() {
        public void onReceive(Context ctxt, Intent intent) {
            pDialog.dismiss();
            play();
        }
    };

    onImgComplete = new BroadcastReceiver() {
        public void onReceive(Context ctxt, Intent intent) {
            pDialog.dismiss();
            Intent emailIntent = new Intent(Intent.ACTION_SEND); 
            emailIntent.setType("image/jpeg");
            emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{});    
            emailIntent.putExtra(Intent.EXTRA_SUBJECT, intent_type_string +" - " + item.name);
            emailIntent.putExtra(Intent.EXTRA_TEXT, intent_msg + "\nDownload EasyFind:\nhttp://yahoo.com.hk");
            emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tmp_img));
            startActivity(emailIntent);
        }
    };

How can I separate them?


Solution

  • You could register just one receiver. And in it's onReceive method the intent argument is supposed to have a long extra with the download ID:

    long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
    

    This is an ID that you should save when starting the download:

    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    Request request = new Request(Uri.parse("YOUR_LINK"));
    long queueID = dm.enqueue(request);
    

    Next you can extract the necessary data about the downloaded file:

    Query query = new Query();
    query.setFilterById(queueID);
    Cursor c = dm.query(query);
    if (c.moveToFirst()) {
        String uriString = c.getString(
            c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
        String mediaType = c.getString(
            c.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
        //TODO IMPLEMENT
    }
    

    NOTE: the Query used is DownloadManager.Query