public class DownloadUtil {
//-1 是未下载 0 是正在下载 1是已经下载
public static final int NOT_DOWNLOAD = -1;
public static final int DOWNLOADING = 0;
public static final int DOWNLOADED = 1;
private static DownloadUtil downloadUtil;
private final OkHttpClient okHttpClient;
private Queue callQueue = new ArrayDeque<>();
Call call;
public static DownloadUtil get() {
if (downloadUtil == null) {
downloadUtil = new DownloadUtil();
}
return downloadUtil;
}
private DownloadUtil() {
okHttpClient = new OkHttpClient();
}
/**
* @param url 下载连接
* @param destFileDir 下载的文件储存目录
* @param destFileName 下载文件名称
* @param listener 下载监听
*/
public void download(final String url, final String destFileDir, final String destFileName, final OnDownloadListener listener) {
Request request = new Request.Builder().url(url).build();
call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 下载失败监听回调
listener.onDownloadFailed(e);
callQueue.remove(call);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
callQueue.add(call);
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
// 储存下载文件的目录
File dir = new File(destFileDir);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, destFileName);
try {
is = response.body().byteStream();
long total = response.body().contentLength(); //文件的总大小
fos = new FileOutputStream(file);
long sum = 0; //已下载文件大小
long beforeTime = System.currentTimeMillis();// 前一秒
long secondCount = 0; // 每次的下载量
int surplus = 0;
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
sum += len;
int progress = (int) (sum * 1.0f / total * 100);
// 计算每秒的下载量并进行回调
long currentTime = System.currentTimeMillis();
if (currentTime - beforeTime > 1000) {
if (secondCount != 0) {
surplus = (int) ((total - sum) / secondCount);
listener.onSurplus(surplus);
beforeTime = currentTime;
secondCount = 0;
}
} else {
secondCount += len;
}
// 下载中更新进度条
listener.onDownloading(progress);
}
fos.flush();
// 下载完成
callQueue.remove(call);
listener.onDownloadSuccess(file);
} catch (Exception e) {
if (file != null && file.exists()) {
file.delete();
}
listener.onDownloadFailed(e);
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
}
try {
if (fos != null)
fos.close();
} catch (IOException e) {
}
}
}
});
}
public void cancel() {
if (call != null) {
call.cancel();
}
}
public void cancelAll () {
Call call ;
while ((call = callQueue.poll()) != null) {
call.cancel();
// callQueue.remove(call);
}
}
public interface OnDownloadListener {
/**
* @param file 下载成功后的文件
*/
void onDownloadSuccess(File file);
/**
* @param progress 下载进度
*/
void onDownloading(int progress);
/**
* @param surplus 剩余时间
*/
void onSurplus(int surplus);
/**
* @param e 下载异常信息
*/
void onDownloadFailed(Exception e);
}
}