DownloadManager各种使用姿势

2018-04-30  本文已影响83人  键盘走过的日子

DownloadManager是Android系统自带下载的方法,使用起来也很方便。
具体步骤如下:

一、添加权限。

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Android版本如果大于等于6.0要动态申请权限。

二、构建Request对象。

DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);   //显示通知栏
request.setDestinationInExternalPublicDir("DOWNLOAD", fileName);//设置下载路径以及文件名字

三、开始下载

taskId = downloadManager.enqueue(buildRequest(downloadUrl, fileName));

将任务加入下载队列并返回taskId,taskId是数据库中的key,数据库是系统自动创建的,root之后的手机可以导出来查看,可以通过taskid查询一次下载的所有属性,包括下载文件总大小、存储路径以及下载状态等等。

四、判断任务下载状态。

有时候我们为了防止重复下载,可以判断其下载状态再决定是否重新下载。

private boolean isDownloading(String url) {
  DownloadManager.Query query = new DownloadManager.Query();
  query.setFilterByStatus(DownloadManager.STATUS_RUNNING | DownloadManager.STATUS_PENDING);
  Cursor cursor = downloadManager.query(query);
  if(cursor.moveToFirst()) {
    if (cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI)).equals(url)) {
      Toast.makeText(this, "任务已经存在", Toast.LENGTH_SHORT).show();
      cursor.close();
      return true;
    }
   }
    cursor.close();
    return false;
}

五、查询下载进度

数据库中并没有提供可以直接可以查询进度的字段,不过可以通过已下载文件大小和文件总大小算出来进度。

private int updateProgress() {
    DownloadManager.Query query = new DownloadManager.Query();
    query.setFilterById(taskId);
    Cursor cursor = downloadManager.query(query);
    if (cursor.moveToFirst()) {
        int storeSize = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
        int totalSize = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
        return storeSize * 100 / totalSize;
    }
    cursor.close();
    return 0;
}

DownloadManager还有很多功能,暂时先写这么几个。

上一篇下一篇

猜你喜欢

热点阅读