前言
APP中难免会使用到下载文件、更新APP的功能,而我们自己处理下载流程往往都很复杂的,要考虑http请求、下载进度监听、下载UI提示信息等等。google官方已经封装好了专门用于下载的类,我们可以直接使用这个类进行下载即可。
DownloadManger是android 2.3(API 9)开始提供的系统服务,用于处理长时间的下载操作。应用场景是客户端请求一个URL地址去下载一个目标文件。DownloadManger可以构建一个后台下载服务,在发生故障或连接更改、重新启动系统等情况后,处理HTTP连接并重试下载。
代码
下载监听接口
package com.hyfun.downloadmanager.support;
/**
* Created by HyFun on 2019/05/27.
* Email: 775183940@qq.com
* Description:
*/
public interface AndroidDownloadManagerListener {
void onPrepare();
void onSuccess(String path);
void onFailed(Throwable throwable);
}
下载管理类
package com.hyfun.downloadmanager.support;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import java.io.File;
/**
* Created by HyFun on 2019/05/27.
* Email: 775183940@qq.com
* <p>
* https://qd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk
* <p>
* Description: 使用android系统自带的download manager 进行下载apk文件
* <p>
* 只负责下载
*/
public class AndroidDownloadManager {
private DownloadManager downloadManager;
private Context context;
private long downloadId;
private String url;
private String name;
private String path;
private AndroidDownloadManagerListener listener;
public AndroidDownloadManager(Context context, String url) {
this(context, url, getFileNameByUrl(url));
}
public AndroidDownloadManager(Context context, String url, String name) {
this.context = context;
this.url = url;
this.name = name;
}
public AndroidDownloadManager setListener(AndroidDownloadManagerListener listener) {
this.listener = listener;
return this;
}
/**
* 开始下载
*/
public void download() {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
//移动网络情况下是否允许漫游
request.setAllowedOverRoaming(false);
//在通知栏中显示,默认就是显示的
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
request.setTitle(name);
request.setDescription("文件正在下载中......");
request.setVisibleInDownloadsUi(true);
//设置下载的路径
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), name);
request.setDestinationUri(Uri.fromFile(file));
path = file.getAbsolutePath();
//获取DownloadManager
if (downloadManager == null) {
downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
}
//将下载请求加入下载队列,加入下载队列后会给该任务返回一个long型的id,通过该id可以取消任务,重启任务、获取下载的文件等等
if (downloadManager != null) {
if (listener != null) {
listener.onPrepare();
}
downloadId = downloadManager.enqueue(request);
}
//注册广播接收者,监听下载状态
context.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
//广播监听下载的各个状态
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
DownloadManager.Query query = new DownloadManager.Query();
//通过下载的id查找
query.setFilterById(downloadId);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
switch (status) {
//下载暂停
case DownloadManager.STATUS_PAUSED:
break;
//下载延迟
case DownloadManager.STATUS_PENDING:
break;
//正在下载
case DownloadManager.STATUS_RUNNING:
break;
//下载完成
case DownloadManager.STATUS_SUCCESSFUL:
if (listener != null) {
listener.onSuccess(path);
}
cursor.close();
context.unregisterReceiver(receiver);
break;
//下载失败
case DownloadManager.STATUS_FAILED:
if (listener != null) {
listener.onFailed(new Exception("下载失败"));
}
cursor.close();
context.unregisterReceiver(receiver);
break;
}
}
}
};
// ——————————————————————私有方法———————————————————————
/**
* 通过URL获取文件名
*
* @param url
* @return
*/
private static final String getFileNameByUrl(String url) {
String filename = url.substring(url.lastIndexOf("/") + 1);
filename = filename.substring(0, filename.indexOf("?") == -1 ? filename.length() : filename.indexOf("?"));
return filename;
}
}
使用
new AndroidDownloadManager(this, url)
.setListener(new AndroidDownloadManagerListener() {
@Override
public void onPrepare() {
Log.d(TAG, "onPrepare");
}
@Override
public void onSuccess(String path) {
Log.d(TAG, "onSuccess >>>>" + path);
}
@Override
public void onFailed(Throwable throwable) {
Log.e(TAG, "onFailed", throwable);
}
})
.download();