在一个 activity 中设置两个具有相同意图的广播接收器

Setup two broadcast receiver of same intent inside one activity

一个activity里面有两个下载管理器,为了同一个目的我注册了两个不同的广播接收器。

问题是,没有像"request code"这样的东西,而且两个接收器似乎重叠,有时触发第一个,有时触发第二个。

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);
        }
    };

如何将它们分开?

您可以只注册一个接收器。在它的 onReceive 方法中,intent 参数应该有一个额外的下载 ID:

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

这是您在开始下载时应保存的 ID:

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

接下来您可以提取有关下载文件的必要数据:

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
}

注意:使用的查询是 DownloadManager.Query