Android中使用DownloadManager类来管理数据下载的教程

2019-12-10 18:07:49丽君


附:DownloadManager的一些重要功能和参数整理

DownloadManager类提供了以下几种方法来处理,
long  enqueue(DownloadManager.Request request)   //存入队列一个新的下载项
ParcelFileDescriptor  openDownloadedFile(long id)  //打开一个下载后的文件用于读取,参数中的long型id是一个provider中的一条记录。
Cursor  query(DownloadManager.Query query)  //查询一个下载,返回一个Cursor
int  remove(long... ids)  //取消下载同时移除这些条从下载管理中。
我们可以看到提供的方法都比较简单,给我们操作的最终封装成为一个provider数据库的方式进行添加、查询和移除,但是对于查询和添加任务的细节,我们要看看DownloadManager.Request类和DownloadManager.Query 类了。
一、DownloadManager.Request类的成员和定义

  • DownloadManager.Request  addRequestHeader(String header, String value)  // 添加一个Http请求报头,对于这两个参数,Android开发网给大家举个小例子,比如说User-Agent值可以为Android123或 Windows XP等等了,主要是给服务器提供标识。
  • DownloadManager.Request  setAllowedNetworkTypes(int flags)  //设置允许使用的网络类型,这一步Android 2.3做的很好,目前有两种定义分别为NETWORK_MOBILE和NETWORK_WIFI我们可以选择使用移动网络或Wifi方式来下载。
  • DownloadManager.Request  setAllowedOverRoaming(boolean allowed)  //对于下载,考虑到流量费用,这里是否允许使用漫游。
  • DownloadManager.Request  setDescription(CharSequence description)  //设置一个描述信息,主要是最终显示的notification提示,可以随便写个自己区别
  • DownloadManager.Request  setDestinationInExternalFilesDir(Context context, String dirType, String subPath)  //设置目标存储在外部目录,一般位置可以用 getExternalFilesDir()方法获取。
  • DownloadManager.Request  setDestinationInExternalPublicDir(String dirType, String subPath)  //设置外部存储的公共目录,一般通过getExternalStoragePublicDirectory()方法获取。
  • DownloadManager.Request  setDestinationUri(Uri uri)  //设置需要下载目标的Uri,可以是http、ftp等等了。