一直以来都对android中的DownloadManager很感兴趣,今天抽空搜了搜,研究了一下,以下是一些总结。
1.DownloadManager是Android 2.3引入的,基于http协议,用于处理长时间下载。
2.在Android app里调用DownloadManager非常简单。
首先要在AndroidManifest.xml中申请访问DownloadManager的权限 <permissionandroid:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/>
其次通过SystemService 以获取(DownloadManager)getSystemService(DOWNLOAD_SERVICE);
一个很简单的调用如下所示:Request request = new Request(
enqueue= dm.enqueue(request); //加入下载队列
查看下载结果:
Intent i = new Intent();
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
监听下载结束,启用BroadcastReceiver BroadcastReceiver receiver = newBroadcastReceiver() { @Override public void onReceive(Contextcontext, Intent intent) { String action = intent.getAction(); if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action))
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue); Cursor c = dm.query(query); if(c.moveToFirst()) {
int columnIndex = c .getColumnIndex(DownloadManager.COLUMN_STATUS);if (DownloadManager.STATUS_SUCCESSFUL == c .getInt(columnIndex)){
ImageView view = (ImageView) findViewById(R.id.imageView1); StringuriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
view.setImageURI(Uri.parse(uriString));
}
}
}
}
};
复杂的调用方式有:
ContentValues values = new ContentValues();
values.put(Downloads.URI, url);//指定下载地址
values.put(Downloads.COOKIE_DATA,cookie);//如果下载Server需要cookie,设置cookie
values.put(Downloads.VISIBILITY,Downloads.VISIBILITY_HIDDEN);//设置下载提示是否在屏幕顶部显示
values.put(Downloads.NOTIFICATION_PACKAGE,getPackageName());//设置下载完成之后回调的包名
values.put(Downloads.NOTIFICATION_CLASS,DownloadCompleteReceiver.class.getName());//设置下载完成之后负责接收的Receiver,这个类要继承BroadcastReceiver
values.put(Downloads.DESTINATION,save_path);//设置下载到的路径,这个需要在Receiver里自行处理
values.put(Downloads.TITLE,title);//设置下载任务的名称
this.getContentResolver().insert(Downloads.CONTENT_URI,values);//将其插入到DownloadManager的数据库中,数据库会触发修改事件,启动下载任务
如何为DownloadManager设置代理,比如Wap
values.put(Downloads.PROXY_HOST,"10.0.0.172");
values.put(Downloads.PROXY_PORT,"80");
如何在下载过程中监听下载任务 可以通过监听数据库来实现 DownloadsChangeObserver mDownloadObserver=newDownloadsChangeObserver(Downloads.CONTENT_URI); privateclass DownloadsChangeObserver extends ContentObserver{ publicDownloadsChangeObserver(Uri uri) { super(newHandler()); }DownloadManager位于com.android.app,有兴趣的可以把源码拿下看一下,源码太长,这里就不贴出来了。