有一种方法可以把额外的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中输入两次。
有一种方法可以在DownloadManager的intent注册为actionDownloadManager。ACTION_DOWNLOAD_COMPLETE(例如接收一个布尔值设置为额外的意图)?
。使用你从enqueue()
得到的ID来存储你想要的boolean
在某个持久的地方(例如,在一个文件中),所以当你收到你的广播时,你可以读回那个值。
另外,对于您的代码片段,请记住,在下载完成时,您的进程可能还没有完成。因此,通过registerReceiver()
注册的BroadcastReceiver
可能永远不会被触发。
答案是对的,你不能在DownloadManager的意图中添加额外的东西。但你可以将description设置为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));
}
}