使用DownloadManager下载
来源:互联网 发布:手动记牌器软件 编辑:程序博客网 时间:2024/06/07 00:46
DownloadManager是一个下载管理器,对文件下载进行了封装,我们不用在写代码去请求资源,也不用去处理通知栏逻辑,使用起来非常方便:
/** * 下载文件(封装了通知栏进度、下载提示、点击安装、异常处理和断点续传逻辑) * * @param context * 上下文对象 * @param urlStr * 文件url地址 * @param downloadDir * 本地保存的目录 * @param fileName * 文件名 * @param title * 通知栏提示的标题 * @param description * 通知栏提示的介绍 * @return 下载id */public static long downFile(Context context, String urlStr,String downloadDir, String fileName, String title,String description) {DownloadManager dm = SystemService.getDownloadManager(context);DownloadManager.Request request = new DownloadManager.Request(Uri.parse(urlStr));// 设置下载后存储目录和文件名request.setDestinationInExternalPublicDir(downloadDir, fileName);// 表示允许MediaScanner扫描到这个文件,默认不允许request.allowScanningByMediaScanner();// 设置下载中通知栏提示的标题if (DataUtil.isEmpty(title))title = "安装包下载";request.setTitle(title);// 设置下载中通知栏提示的介绍if (DataUtil.isEmpty(description))description = "安装包正在下载中";request.setDescription(description);// 表示下载完成后显示通知栏提示request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);return dm.enqueue(request);}
另外通过下载id,还可以查询其他东西,不一一介绍了,同时可以注册一个广播用来监听下载完成事件,有时候下载完成需要做一些逻辑处理:
package com.home.receiver;import java.io.File;import android.app.DownloadManager;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import com.home.util.APKUtil;import com.home.util.FileUtil;import com.home.util.SharedUtil;public class DownCompleteReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {long curDownId = SharedUtil.getLong(context, "data", "downId", -1);String fileName = SharedUtil.getString(context, "data", "fileName");long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);if (curDownId == downId) {APKUtil.installAPK(context, FileUtil.getRootPath() + File.separator+ fileName);}}}
0 0
- 使用DownloadManager下载
- 使用Downloadmanager进行下载
- 使用DownloadManager进行文件下载
- 使用DownloadManager实现下载功能
- [Android开发] 使用DownloadManager下载
- 文件下载之使用DownloadManager
- 使用DownloadManager实现文件下载
- 使用DownloadManager实现下载更新
- Android使用DownloadManager下载文件
- 使用Android自带DownloadManager下载文件
- android开发(23)使用DownloadManager下载文件
- 使用Android自带DownloadManager下载文件
- 使用Android自带DownloadManager下载文件
- 使用Android自带DownloadManager下载文件
- 使用Android自带DownloadManager下载文件
- 使用系统下载管理类DownloadManager
- android开发(23)使用DownloadManager下载文件
- 使用 DownloadManager 实现完全在后台下载
- Java中的集合(上)
- 黑马程序员--String类、StringBuffer类和StringBuilder类
- openGL 深度测试
- GNU ARM 汇编伪指令(Assembler Directives)
- 第6周项目1 建立顺序栈算法库
- 使用DownloadManager下载
- 第七周项目2--建立链队算法库
- 十三种基于直方图的图像全局二值化算法原理、实现、代码及效果(转)
- 线程池的原理及实现
- shell date命令使用
- ios app 内存泄露分析
- txt转换pdf格式的通用方法
- js基础知识
- ARM CPSR+SPSR