有一种方法可以在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));
}
}
}
使用intent.getExtras()
我只能获取请求参数。我尝试将广播发送到具有不同操作的同一个接收器(一个使用ACTION_DOWNLOAD_COMPLETED
,另一个是自定义),但我必须发送双重广播,因此它将在onReceive中输入两次。
答案 0 :(得分:6)
有一种方法可以在为DownloadDownloadManager.ACTION_DOWNLOAD_COMPLETE注册的DownloadManager意图中添加额外内容(例如,在意图中接收一个设置为额外的布尔值)?
没有。使用您获得的ID from enqueue()
将您想要的boolean
存储在某个地方(例如,在文件中),这样您就可以在收到广播时重新读取该值。
此外,对于您的代码段,请记住,下载完成后您的进程可能不在周围。因此,BroadcastReceiver
通过registerReceiver()
注册的$value
可能永远不会被触发。
答案 1 :(得分:1)
答案是对的,你不能把额外的东西放到DownloadManager的意图上。但您可以将描述设置为DownloadManager的请求,然后在下载完成后阅读。我认为这对你来说已经足够了。
DownloadManager dm = (DownloadManager) getSystemService(BaseActivity.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse((Constants.ROOT_URL_1 + fileName)));
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle(title)
.setDescription("This is what you need!!!")
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationInExternalPublicDir("/my_folder", title)
.allowScanningByMediaScanner();
您可以在上面看到解密字段。现在,我将在BroadcastReceiver的onReceive方法完成下载后阅读本文。
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor c = ((DownloadManager) getSystemService(BaseActivity.DOWNLOAD_SERVICE)).query(query);
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
String description = c.getString(c.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION));
}
}