为 DownloadManager 的 BroadcastReceiver 设置附加功能 [重复]

2024-05-10

有一种方法可以添加额外内容DownloadManager已登记行动意图DownloadManager.ACTION_DOWNLOAD_COMPLETE(例如,接收一个在意图中设置为额外的布尔值)?

这就是我创建请求的方式:

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

在我的 onComplete 接收器中:

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()我只能获取请求参数。我尝试使用不同的操作将广播发送到同一接收器(其中一个ACTION_DOWNLOAD_COMPLETED,另一个是自定义的),但我必须发送双重广播,因此它会在 onReceive 中输入两次。


有一种方法可以将额外内容放入为 actionDownloadManager.ACTION_DOWNLOAD_COMPLETE 注册的 DownloadManager 意图中(例如,接收在意图中设置为额外内容的布尔值)?

不需要。使用您取回的 IDfrom enqueue() http://developer.android.com/reference/android/app/DownloadManager.html#enqueue%28android.app.DownloadManager.Request%29来存储您想要的boolean某个持久的地方(例如,在文件中),因此您可以在收到广播时读回该值。

另外,对于您的代码片段,请记住,下载完成时您的进程可能尚未存在。你的BroadcastReceiver注册通过registerReceiver()因此,可能永远不会被触发。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为 DownloadManager 的 BroadcastReceiver 设置附加功能 [重复] 的相关文章

随机推荐