【中级——高级迈不过去?】Android高级工程师进阶学习——Android多线程断点续传(系列篇

/**

  • 子程恢复下载的位置

*/

public void onChildResume(long resumeLocation);

/**

  • 恢复位置

*/

public void onResume(long resumeLocation);

/**

  • 停止

*/

public void onStop(long stopLocation);

/**

  • 下载完成

*/

public void onComplete();

}

该类是下载监听接口

DownloadListener.java

import java.net.HttpURLConnection;

/**

  • 下载监听

*/

public class DownloadListener implements IDownloadListener {

@Override

public void onResume(long resumeLocation) {

}

@Override

public void onCancel() {

}

@Override

public void onFail() {

}

@Override

public void onPreDownload(HttpURLConnection connection) {

}

@Override

public void onProgress(long currentLocation) {

}

@Override

public void onChildComplete(long finishLocation) {

}

@Override

public void onStart(long startLocation) {

}

@Override

public void onChildResume(long resumeLocation) {

}

@Override

public void onStop(long stopLocation) {

}

@Override

public void onComplete() {

}

}

下载参数实体


/**

  • 子线程下载信息类

*/

private class DownloadEntity {

//文件总长度

long fileSize;

//下载链接

String downloadUrl;

//线程Id

int threadId;

//起始下载位置

long startLocation;

//结束下载的文章

long endLocation;

//下载文件

File tempFile;

Context context;

public DownloadEntity(Context context, long fileSize, String downloadUrl, File file, int threadId, long startLocation, long endLocation) {

this.fileSize = fileSize;

this.downloadUrl = downloadUrl;

this.tempFile = file;

this.threadId = threadId;

this.startLocation = startLocation;

this.endLocation = endLocation;

this.context = context;

}

}

该类是下载信息配置类,每一条子线程的下载都需要一个下载实体来配置下载信息。

下载任务线程

/**

  • 多线程下载任务类

*/

private class DownLoadTask implements Runnable {

private static final String TAG = “DownLoadTask”;

private DownloadEntity dEntity;

private String configFPath;

public DownLoadTask(DownloadEntity downloadInfo) {

this.dEntity = downloadInfo;

configFPath = dEntity.context.getFilesDir().getPath() + “/temp/” + dEntity.tempFile.getName() + “.properties”;

}

@Override

public void run() {

try {

L.d(TAG, “线程_” + dEntity.threadId + “_正在下载【” + "开始位置 : " + dEntity.startLocation + “,结束位置:” + dEntity.endLocation + “】”);

URL url = new URL(dEntity.downloadUrl);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

//在头里面请求下载开始位置和结束位置

conn.setRequestProperty(“Range”, “bytes=” + dEntity.startLocation + “-” + dEntity.endLocation);

conn.setRequestMethod(“GET”);

conn.setRequestProperty(“Charset”, “UTF-8”);

conn.setConnectTimeout(TIME_OUT);

conn.setRequestProperty(“User-Agent”, “Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)”);

conn.setRequestProperty(“Accept”, “image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, /”);

conn.setReadTimeout(2000); //设置读取流的等待时间,必须设置该参数

InputStream is = conn.getInputStream();

//创建可设置位置的文件

RandomAccessFile file = new RandomAccessFile(dEntity.tempFile, “rwd”);

//设置每条线程写入文件的位置

file.seek(dEntity.startLocation);

byte[] buffer = new byte[1024];

int len;

//当前子线程的下载位置

long currentLocation = dEntity.startLocation;

while ((len = is.read(buffer)) != -1) {

if (isCancel) {

L.d(TAG, “++++++++++ thread_” + dEntity.threadId + “_cancel ++++++++++”);

break;

}

if (isStop) {

break;

}

//把下载数据数据写入文件

file.write(buffer, 0, len);

synchronized (DownLoadUtil.this) {

mCurrentLocation += len;

mListener.onProgress(mCurrentLocation);

}

currentLocation += len;

}

file.close();

is.close();

if (isCancel) {

synchronized (DownLoadUtil.this) {

mCancelNum++;

if (mCancelNum == THREAD_NUM) {

File configFile = new File(configFPath);

if (configFile.exists()) {

configFile.delete();

}

if (dEntity.tempFile.exists()) {

dEntity.tempFile.delete();

}

L.d(TAG, “++++++++++++++++ onCancel +++++++++++++++++”);

isDownloading = false;

mListener.onCancel();

System.gc();

}

}

return;

}

//停止状态不需要删除记录文件

if (isStop) {

synchronized (DownLoadUtil.this) {

mStopNum++;

String location = String.valueOf(currentLocation);

L.i(TAG, “thread_” + dEntity.threadId + "_stop, stop location ==> " + currentLocation);

writeConfig(dEntity.tempFile.getName() + “record” + dEntity.threadId, location);

if (mStopNum == THREAD_NUM) {

L.d(TAG, “++++++++++++++++ onStop +++++++++++++++++”);

isDownloading = false;

mListener.onStop(mCurrentLocation);

System.gc();

}

}

return;

}

L.i(TAG, “线程【” + dEntity.threadId + “】下载完毕”);

writeConfig(dEntity.tempFile.getName() + “state” + dEntity.threadId, 1 + “”);

mListener.onChildComplete(dEntity.endLocation);

mCompleteThreadNum++;

if (mCompleteThreadNum == THREAD_NUM) {

File configFile = new File(configFPath);

if (configFile.exists()) {

configFile.delete();

}

mListener.onComplete();

isDownloading = false;

System.gc();

}

} catch (MalformedURLException e) {

e.printStackTrace();

isDownloading = false;

mListener.onFail();

} catch (IOException e) {

FL.e(this, “下载失败【” + dEntity.downloadUrl + “】” + FL.getPrintException(e));

isDownloading = false;

mListener.onFail();

} catch (Exception e) {

FL.e(this, “获取流失败” + FL.getPrintException(e));

isDownloading = false;

mListener.onFail();

}

}

这个是每条下载子线程的下载任务类,子线程通过下载实体对每一条线程进行下载配置,由于在多断点续传的概念里,停止表示的是暂停状态,而恢复表示的是线程从记录的断点重新进行下载,所以,线程处于停止状态时是不能删除记录文件的。

下载入口

/**

  • 多线程断点续传下载文件,暂停和继续

  • @param context 必须添加该参数,不能使用全局变量的context

  • @param downloadUrl 下载路径

  • @param filePath 保存路径

  • @param downloadListener 下载进度监听 {@link DownloadListener}

*/

public void download(final Context context, @NonNull final String downloadUrl, @NonNull final String filePath,

@NonNull final DownloadListener downloadListener) {

isDownloading = true;

mCurrentLocation = 0;

isStop = false;

isCancel = false;

mCancelNum = 0;

mStopNum = 0;

final File dFile = new File(filePath);

//读取已完成的线程数

final File configFile = new File(context.getFilesDir().getPath() + “/temp/” + dFile.getName() + “.properties”);

try {

if (!configFile.exists()) { //记录文件被删除,则重新下载

newTask = true;

FileUtil.createFile(configFile.getPath());

} else {

newTask = false;

}

} catch (Exception e) {

e.printStackTrace();

mListener.onFail();

return;

}

newTask = !dFile.exists();

new Thread(new Runnable() {

@Override

public void run() {

try {

mListener = downloadListener;

URL url = new URL(downloadUrl);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod(“GET”);

conn.setRequestProperty(“Charset”, “UTF-8”);

conn.setConnectTimeout(TIME_OUT);

conn.setRequestProperty(“User-Agent”, “Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)”);

conn.setRequestProperty(“Accept”, “image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, /”);

conn.connect();

int len = conn.getContentLength();

if (len < 0) { //网络被劫持时会出现这个问题

mListener.onFail();

return;

}

int code = conn.getResponseCode();

if (code == 200) {

int fileLength = conn.getContentLength();

//必须建一个文件

FileUtil.createFile(filePath);

RandomAccessFile file = new RandomAccessFile(filePath, “rwd”);

//设置文件长度

file.setLength(fileLength);

mListener.onPreDownload(conn);

//分配每条线程的下载区间

Properties pro = null;

pro = Util.loadConfig(configFile);

int blockSize = fileLength / THREAD_NUM;

SparseArray tasks = new SparseArray<>();

for (int i = 0; i < THREAD_NUM; i++) {

long startL = i * blockSize, endL = (i + 1) * blockSize;

Object state = pro.getProperty(dFile.getName() + “state” + i);

if (state != null && Integer.parseInt(state + “”) == 1) { //该线程已经完成

mCurrentLocation += endL - startL;

L.d(TAG, “++++++++++ 线程_” + i + “_已经下载完成 ++++++++++”);

mCompleteThreadNum++;

if (mCompleteThreadNum == THREAD_NUM) {

if (configFile.exists()) {

configFile.delete();

}

mListener.onComplete();

isDownloading = false;

System.gc();

return;

}

continue;

}

//分配下载位置

Object record = pro.getProperty(dFile.getName() + “record” + i);

if (!newTask && record != null && Long.parseLong(record + “”) > 0) { //如果有记录,则恢复下载

Long r = Long.parseLong(record + “”);

mCurrentLocation += r - startL;

L.d(TAG, “++++++++++ 线程_” + i + “_恢复下载 ++++++++++”);

mListener.onChildResume®;

startL = r;

}

if (i == (THREAD_NUM - 1)) {

endL = fileLength;//如果整个文件的大小不为线程个数的整数倍,则最后一个线程的结束位置即为文件的总长度

}

DownloadEntity entity = new DownloadEntity(context, fileLength, downloadUrl, dFile, i, startL, endL);

DownLoadTask task = new DownLoadTask(entity);

tasks.put(i, new Thread(task));

}

if (mCurrentLocation > 0) {

mListener.onResume(mCurrentLocation);

} else {

mListener.onStart(mCurrentLocation);

}

for (int i = 0, count = tasks.size(); i < count; i++) {

Thread task = tasks.get(i);

if (task != null) {

task.start();

}

}

} else {

FL.e(TAG, “下载失败,返回码:” + code);

isDownloading = false;

System.gc();

mListener.onFail();

}

} catch (IOException e) {

FL.e(this, “下载失败【downloadUrl:” + downloadUrl + “】\n【filePath:” + filePath + “】” + FL.getPrintException(e));

isDownloading = false;

mListener.onFail();

}

最后

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助

因此我收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点!不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

  • filePath + “】” + FL.getPrintException(e));

isDownloading = false;

mListener.onFail();

}

最后

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助

因此我收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

[外链图片转存中…(img-RP0aTJJt-1715800490081)]

[外链图片转存中…(img-WkUbduBR-1715800490084)]

[外链图片转存中…(img-eIdf4FlR-1715800490085)]

[外链图片转存中…(img-vLQty0ui-1715800490086)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点!不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

  • 11
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值