DownLoadManager解析

来源:互联网 发布:anaconda与python版本 编辑:程序博客网 时间:2024/06/08 11:25

DownLoadManager解析
1、使用DownLoadManager
DownLoadManager downloadManager =(DownLoadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri=Uri.parse("http://baidu.com/laiqingping.zip");
DownLoadManager.Request request =new Request(uri);
long reference =downloadManager.enqueue(request);

2、Request中方法解析
addRequestHeader();setMimeType();给请求添加http报文头和返回的MIME类型。
request.setAllownetWorkType(Request.NETWORK_WIFI); 设置下载的网络类型,这里设置的是只能在wifi条件下下载;
setAllowedOverRoaming(); 设置是否允许漫游网络下下载。可预见性的阻止漫游情况下的下载
setRecommendedMaxBytesOverMobile() 设置推荐的数据链接中最大的bytes数来确定是否使用wifi下载

3、对下载完成的处理
当下载完成,DownloadManager 会发送一个广播DownloadManager.ACTION_DOWNLOAD_COMPLETE;
可以通过注册接受该广播的BoadcastReceiver接收该广播,对下载完成的出处理
举个栗子
BoadcastReceiver downloadComplete=new BoadcastReceiver(){
@Override
public void onReceive(Context context,Intent bundle){
int reference=bundle.getLongExtra(DownLoadManager.EXTRA_DOWNLOAD_ID,-1);

}
}
IntentFilter intentFilter=new IntentFilter(DownLoadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceoiver(downloadComplete,intentFilter);

4、默认情况下 DownLoadManagerw为其中每一个下载创建一个Download Notification
最好为ACTION_NOTIFICATION_CLICKED注册一个Receiver
BoadcastReceiver boadcastReceiver =new BoadcastReceiver(){
@Override
public void onReceive(Context Context,Intent intent){
int[] references=intent.getLongArrayExtra(DoadloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
for(long reference:references){
if(reference==mydownreference){
//点击完成后的操作
}
}
}
}
IntentFilter intentFilter=new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED);
registerReceiver(boadcastReceiver,intentFilter);

5、自定义Notification
request.setTitle("title");
request.setDescription("description");
request.setNotificationVisibility(Request.VISIBILITY_HIDDEN);//在下载过程中不显示Notification,需要DOWNLOAD_WITHOUT_NOTIFICATION <use_permission>
Request.VISIBILITY_VISIBLE_COMPLETE //

6、指定下载位置
request.setDestinationUri(Uri uri);  //Uri.fromFile(file);

 

7、其他
allowScaningByMediaScanner();//是否可以被MediaScanner扫描,默认情况下是不会被MediaScanner扫描


8、取消下载

DownLoadManager.remove(int reference) 方法 取消一个正在等待的下载 中止一个正在进行的下载 删除一个完成的下载

9、查询DownloadManager
使用Cursor cursor=DownloadManager.query(DownloadManger.Query query);查询下载的状态、进度和详细信息;
其中 DownloadManager.Query 对象是对查询结果进行过滤 Query.setFilterById();指定相应的下载Id    Query.setFilterStatus(DownloadManager.STATUS_*) 指定下载的状态
返回的Cursor对象和数据库查询出的Cursor是一样的;
可以通过DownloadManager.COLUMN_* 查询Cursor中的列,可以得到下载的详细信息;

其如果查询的状态是DownloadManager.STATUS_PAUSED  通过DownloadManager.PAUSED_* 获取暂停的原因;
如果状态为 DownloadManager.STATU_FAILED    通过DownloadManager.ERROR_* 获取下载失败的原因;

0 0
原创粉丝点击