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

Android 多執行緒下載實作:從原理到斷點續傳

編輯:關於 Android 程式設計

要談多執行緒下載,得先理解單執行緒下載為什麼慢。

單執行緒就是一個任務从头做到尾,速度自然受限。

而三個執行緒分頭下載同一個檔案的不同片段,總比一個執行緒獨力完成快得多。

關鍵在於:每個執行緒負責哪一段位元組範圍,以及各自把資料寫到檔案的哪個位置。想清楚這兩件事,就可以開始寫程式了。

步驟一:取得檔案大小並切分區間

要分配下載量,首先得知道檔案有多大。我在本機架了一個服務,檔案名為 Wireshark.exe:

public void downloade(View v) {
    Thread thread = new Thread() {
        // 伺服器位址
        String path = "https://192.168.1.123:8080/Wireshark.exe";

        @Override
        public void run() {
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                conn.setReadTimeout(5000);

                if (conn.getResponseCode() == 200) {
                    // 取得檔案總大小
                    int length = conn.getContentLength();
                    // 每個執行緒要下載的大小
                    int size = length / threadCount;

                    for (int i = 0; i < threadCount; i++) {
                        int startIndex = i * size;
                        int endIndex = (i + 1) * size - 1;
                        // 最後一個執行緒要吃到檔案結尾
                        if (i == threadCount - 1) {
                            endIndex = length - 1;
                        }
                        System.out.println("線程" + i + "的下載區間為:" + startIndex + "---" + endIndex);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    thread.start();
}

輸出結果:

可以看到區間計算正確,總大小為 29849552 位元組。這裡有個細節必須注意:最後一個執行緒的 endIndex 要特別指定為 length - 1,因為檔案大小未必能被執行緒數整除,餘數會落在最后一段。

步驟二:多執行緒實際下載

下載開始前,先在儲存裝置上配置一個與目標檔案等大的暫存檔,這樣可以避免下載途中因空間不足而失敗。

System.out.println("線程" + i + "的下載區間為:" + startIndex + "---" + endIndex);
// 啟動 threadCount 個執行緒
new downloadThread(startIndex, endIndex, i).start();
class downloadThread extends Thread {
    int startIndex;   // 起始位置
    int endIndex;     // 結束位置
    int threadId;     // 執行緒編號

    public downloadThread(int startIndex, int endIndex, int threadId) {
        super();
        this.startIndex = startIndex;
        this.endIndex = endIndex;
        this.threadId = threadId;
    }

    @Override
    public void run() {
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);

            // 透過 Range 標頭只請求本執行緒負責的區間
            conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);

            // 部分內容請求成功會回傳 206
            if (conn.getResponseCode() == 206) {
                InputStream is = conn.getInputStream();
                byte[] b = new byte[1024];
                int len = 0;
                int total = 0;

                File file = new File(Environment.getExternalStorageDirectory(), filename);
                RandomAccessFile raf = new RandomAccessFile(file, "rwd");
                // 把寫入位置移到本執行緒的起點
                raf.seek(startIndex);

                while ((len = is.read(b)) != -1) {
                    raf.write(b, 0, len);
                    total += len;
                    System.out.println("線程" + threadId + "下載了" + total);
                }
                System.out.println("線程" + threadId + "---------------下載完畢-------------------");
                raf.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

這裡有兩個關鍵 API:Range 請求標頭讓伺服器只回傳指定區間(回應碼為 206 而非 200),RandomAccessFile.seek() 則讓我們能把資料寫到檔案的任意偏移位置。兩者搭配,多個執行緒才能各自寫入同一個檔案而不互相覆蓋。

步驟三:顯示下載進度

下載過程要讓使用者看得到進度。先把 ProgressBar 的最大值設為檔案總大小:

int length = conn.getContentLength();
pBar.setMax(length);
int size = length / threadCount;

每寫入一段就累加目前進度,注意這裡要統計的是所有執行緒的總和:

raf.write(b, 0, len);
total += len;
System.out.println("線程" + threadId + "下載了" + total);
currProgress += len;
pBar.setProgress(currProgress);

文字標籤顯示百分比時,用 Handler 更新 UI:

Handler handler = new Handler() {
    public void handleMessage(android.os.Message msg) {
        // 轉成 long 運算,避免 int 溢位
        tView.setText((long) pBar.getProgress() * 100 / pBar.getMax() + "%");
    }
};

效果如下:

步驟四:實作斷點續傳

多執行緒下載完成後,下一個問題是:如果中途斷網或被終止,重新開始時能否接續?做法是把每個執行緒已下載的位元組數寫入一個進度檔,重來時讀回並調整起始位置。

啟動時先讀取上次的進度:

File bakFile = new File(Environment.getExternalStorageDirectory(), threadId + ".txt");
try {
    if (bakFile.exists()) {
        FileInputStream fis = new FileInputStream(bakFile);
        BufferedReader bReader = new BufferedReader(new InputStreamReader(fis));
        // 讀出上次已下載的量,加到原本的起始位置上
        int lastProgress = Integer.parseInt(bReader.readLine());
        startIndex += lastProgress;

        // 同步更新進度條與文字
        currProgress += lastProgress;
        pBar.setProgress(currProgress);
        handler.sendEmptyMessage(1);
        fis.close();
    }
} catch (Exception e) {
    e.printStackTrace();
}

下載迴圈中,每寫入一段就把累計進度存回設定檔:

while ((len = is.read(b)) != -1) {
    raf.write(b, 0, len);
    total += len;
    System.out.println("線程" + threadId + "下載了" + total);

    currProgress += len;
    pBar.setProgress(currProgress);
    handler.sendEmptyMessage(1);

    // 將目前進度寫入設定檔,供下次續傳使用
    RandomAccessFile bakRaFile = new RandomAccessFile(bakFile, "rwd");
    bakRaFile.write((total + "").getBytes());
    bakRaFile.close();
}

如此一來,斷點續傳就能正常工作了。

下載完成的檔案可以正常執行(我把範例檔案換成了體積較小的 feather 檔案,Wireshark 實在太大)。

幾個實務提醒

Range 支援是前提。伺服器必須回應 206 並提供 Accept-Ranges 標頭,否則整個方案不成立。實作前最好先確認後端支援情況。

進度檔的寫入頻率。上面範例每寫 1KB 就存檔一次,I/O 太頻繁。實務上可以改成每完成固定百分比或每隔數秒才落盤,兼顧效能與安全性。

執行緒數不是越多越好。過多執行緒會導致頻寬競爭與連線開銷上升,一般 3 到 5 條是常見的甜蜜點。

權限與相容性。寫入外部儲存需要相關權限,Android 6.0 以上還要處理動態授權;Android 10 以上則建議改用儲存空間存取架構或 app 專屬目錄。

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