Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 多線程下載與斷點續傳的完整實現

編輯:Android 開發教學

項目源碼:https://github.com/Wang-Jun-Chao/AndroidProjects

為什麼多線程更快

原理並不神秘:服務器 CPU 分配給每條連接的時間片大致相同,帶寬也是平均分配。也就是說,客戶端開啟的線程越多,能搶到的服務器資源就越多。三條線程下載同一個文件,通常比單線程快接近三倍。

第一步:確定每條線程下載多少數據

先發一個 HTTP 請求拿到文件總長度:

String path = "下載地址";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);

拿到長度後,創建一個等長的臨時文件把空間先佔住,這樣後續各線程可以直接定位寫入:

if (conn.getResponseCode() == 200) {
    length = conn.getContentLength();
    RandomAccessFile raf = new RandomAccessFile(getFileName(path), "rws");
    raf.setLength(length);
    raf.close();
}

然後把總長度平均分成 THREAD_COUNT 份:

blockSize = length / THREAD_COUNT;

第二步:計算每條線程的起止位置

這是關鍵的一步。最後一條線程要特意把 endIndex 設為文件總長度,否則除不盡的餘數會丟失:

for (int i = 1; i <= THREAD_COUNT; ++i) {
    startIndex = (i - 1) * blockSize;
    endIndex = i * blockSize - 1;
    if (i == THREAD_COUNT) {
        endIndex = length;
    }
    new DownLoadThread(startIndex, endIndex, i).start();
}

第三步:帶 Range 頭發起分段請求

多線程下載的核心在於 HTTP 的 Range 請求頭,格式是 Range: bytes=起始位置-結束位置:

String path = "下載地址";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
conn.connect();

// 下載請求到的數據,寫入臨時文件對應位置
if (conn.getResponseCode() == 206) {
    InputStream is = conn.getInputStream();
    RandomAccessFile raf = new RandomAccessFile(getFileName(path), "rws");
    raf.seek(startIndex);
    byte[] b = new byte[1024];
    int len;
    while ((len = is.read(b)) != -1) {
        raf.write(b, 0, len);
    }
    raf.close();
}

注意狀態碼是 206(Partial Content)而非 200,這是服務器確認支持分段傳輸的標誌。同時 raf.seek(startIndex) 不可省略,它決定數據寫入文件的哪個偏移量。

第四步:加上斷點續傳

思路很簡單:用一個變量記錄每條線程已下載的字節數,加上該線程的起始位置,就得到下次續傳的起點,把這個值寫入緩存文件。

total = 0;
while ((len = is.read(b)) != -1) {
    raf.write(b, 0, len);
    total += len;
    RandomAccessFile raf2 = new RandomAccessFile(threadId + ".txt", "rws");
    raf2.write((startIndex + total + "").getBytes());
    raf2.close();
}

下次下載啟動時,先讀緩存文件拿回新的起始位置:

FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String text = br.readLine();
int newStartIndex = Integer.parseInt(text);
// 把讀到的值作為新的開始位置
startIndex = newStartIndex;
fis.close();

三條線程全部完成後,清理緩存文件:

RUNNING_THREAD--;
if (RUNNING_THREAD == 0) {
    for (int i = 1; i <= 3; i++) {
        File f = new File(i + ".txt");
        f.delete();
    }
}

移植到手機端

上面的代碼稍作調整即可在 Android 上跑:把文件路徑換成 Android 的存儲目錄,並在清單文件中添加網絡訪問與外部存儲讀寫權限。

用進度條展示整體進度

拿到總長度後設置進度條上限:

pb.setMax(length);

進度條要體現三條線程的合計進度,所以定義一個全局變量累計:

int progress = 0;

每讀到一段數據就累加並刷新:

// 刷新進度條
while ((len = is.read(b)) != -1) {
    raf.write(b, 0, len);
    progress += len;
    pb.setProgress(progress);
}

斷點續傳時有個容易漏掉的細節:從新位置開始下載,進度條也要相應跳躍,需要把「之前已經下載的量」補回去:

FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String text = br.readLine();
int newStartIndex = Integer.parseInt(text);
int alreadyDownload = newStartIndex - startIndex;
progress += alreadyDownload;

顯示百分比

tv.setText(progress * 100 / pb.getMax() + "%");

更省事的做法:xUtils 的 HttpUtils

如果你不想自己造輪子,HttpUtils 本身就支持多線程斷點續傳,用法非常簡潔。

創建對象:

HttpUtils http = new HttpUtils();

下載並回調:

http.download(url, target, true, true, new RequestCallBack<File>() {

    @Override
    public void onSuccess(ResponseInfo<File> arg0) {
        tv.setText("下載成功:" + arg0.result.getPath());
    }

    @Override
    public void onFailure(HttpException arg0, String arg1) {
        tv.setText("下載失敗:" + arg1);
    }

    @Override
    public void onLoading(long total, long current, boolean isUploading) {
        super.onLoading(total, current, isUploading);
        pb.setMax((int) total);
        pb.setProgress((int) current);
        tv_progress.setText(current * 100 / total + "%");
    }
});

更多內容:https://www.bianceng.cn/OS/extra/

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved