怎么在Android中利用多線程實現一個斷點續傳下載功能?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
原理
其實斷點續傳的原理很簡單,從字面上理解,所謂斷點續傳就是從停止的地方重新下載。
斷點:線程停止的位置。
續傳:從停止的位置重新下載。
用代碼解析就是:
斷點:當前線程已經下載完成的數據長度。
續傳:向服務器請求上次線程停止位置之后的數據。
原理知道了,功能實現起來也簡單。每當線程停止時就把已下載的數據長度寫入記錄文件,當重新下載時,從記錄文件讀取已經下載了的長度。而這個長度就是所需要的斷點。
續傳的實現也簡單,可以通過設置網絡請求參數,請求服務器從指定的位置開始讀取數據。
而要實現這兩個功能只需要使用到HttpURLconnection里面的setRequestProperty方法便可以實現.
public void setRequestProperty(String field, String newValue)
如下所示,便是向服務器請求500-1000之間的500個byte:
conn.setRequestProperty("Range", "bytes=" + 500 + "-" + 1000);以上只是續傳的一部分需求,當我們獲取到下載數據時,還需要將數據寫入文件,而普通發File對象并不提供從指定位置寫入數據的功能,這個時候,就需要使用到RandomAccessFile來實現從指定位置給文件寫入數據的功能。
public void seek(long offset)
如下所示,便是從文件的的第100個byte后開始寫入數據。
raFile.seek(100);
而開始寫入數據時還需要用到RandomAccessFile里面的另外一個方法
public void write(byte[] buffer, int byteOffset, int byteCount)
該方法的使用和OutputStream的write的使用一模一樣…
以上便是斷點續傳的原理。
多線程斷點續傳
而多線程斷點續傳便是在單線程的斷點續傳上延伸的,而多線程斷點續傳是把整個文件分割成幾個部分,每個部分由一條線程執行下載,而每一條下載線程都要實現斷點續傳功能。
為了實現文件分割功能,我們需要使用到HttpURLconnection的另外一個方法:
public int getContentLength()
當請求成功時,可以通過該方法獲取到文件的總長度。
每一條線程下載大小 = fileLength / THREAD_NUM
如下圖所示,描述的便是多線程的下載模型:

在多線程斷點續傳下載中,有一點需要特別注意:
由于文件是分成多個部分是被不同的線程的同時下載的,這就需要,每一條線程都分別需要有一個斷點記錄,和一個線程完成狀態的記錄;
如下圖所示:

只有所有線程的下載狀態都處于完成狀態時,才能表示文件已經下載完成。
實現記錄的方法多種多樣,我這里采用的是JDK自帶的Properties類來記錄下載參數。
斷點續傳結構
通過原理的了解,便可以很快的設計出斷點續傳工具類的基本結構圖

IDownloadListener.java
package com.arialyy.frame.http.inf;
import java.net.HttpURLConnection;
/**
* 在這里面編寫你的業務邏輯
*/
public interface IDownloadListener {
/**
* 取消下載
*/
public void onCancel();
/**
* 下載失敗
*/
public void onFail();
/**
* 下載預處理,可通過HttpURLConnection獲取文件長度
*/
public void onPreDownload(HttpURLConnection connection);
/**
* 下載監聽
*/
public void onProgress(long currentLocation);
/**
* 單一線程的結束位置
*/
public void onChildComplete(long finishLocation);
/**
* 開始
*/
public void onStart(long startLocation);
/**
* 子程恢復下載的位置
*/
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<Thread> 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(r);
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();
}
}
}).start();
}其實也沒啥好說的,注釋已經很完整了,需要注意兩點
1、恢復下載時:已下載的文件大小 = 該線程的上一次斷點的位置 - 該線程起始下載位置;
2、為了保證下載文件的完整性,只要記錄文件不存在就需要重新進行下載;
看完上述內容,你們掌握怎么在Android中利用多線程實現一個斷點續傳下載功能的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。