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

Android 開發實戰:多執行緒斷點續傳下載

編輯:關於 Android 程式設計

單執行緒下載最大的問題是慢,而一旦網路中斷就得從頭再來。多執行緒斷點續傳同時解決了這兩件事:把檔案切成多段由多個執行緒平行下載以提升速度,並把每段的下載進度寫入磁碟,中斷後能從上次的位置續傳。

核心原理依賴 HTTP 的 Range 請求標頭,加上 Java 的 RandomAccessFile(可隨意定位寫入位置)。

MainActivity.java

package com.itheima.mobilemultidownload;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {

    static int ThreadCount = 3;
    static int finishedThread = 0;
    int currentProgress;

    String fileName = "QQPlayer.exe";
    // 下載來源
    String path = "https://192.168.13.13:8080/" + fileName;

    private ProgressBar pb;
    private TextView tv;

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            // 用 long 運算,否則檔案很大時進度會變成負數
            tv.setText((long) pb.getProgress() * 100 / pb.getMax() + "%");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pb = (ProgressBar) findViewById(R.id.pb);
        tv = (TextView) findViewById(R.id.tv);
    }

    public void click(View v) {
        Thread t = new Thread() {
            @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();
                        pb.setMax(length);

                        File file = new File(Environment.getExternalStorageDirectory(), fileName);
                        // "rwd" 表示直接寫入磁碟,不經過記憶體緩衝,
                        // 避免斷電時部分資料還沒落盤
                        RandomAccessFile raf = new RandomAccessFile(file, "rwd");
                        raf.setLength(length);   // 預先配置好檔案大小
                        raf.close();

                        // 計算每個執行緒負責多少位元組
                        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;
                            }
                            new DownLoadThread(startIndex, endIndex, i).start();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }

    class DownLoadThread extends Thread {
        int startIndex;
        int endIndex;
        int threadId;

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

        @Override
        public void run() {
            try {
                // 每個執行緒有自己的進度檔,用來記錄已下載的位元組數
                File progressFile = new File(
                        Environment.getExternalStorageDirectory(), threadId + ".txt");

                if (progressFile.exists()) {
                    FileInputStream fis = new FileInputStream(progressFile);
                    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                    int lastProgress = Integer.parseInt(br.readLine());
                    // 把上次的進度加到起始位置上,就完成續傳了
                    startIndex += lastProgress;
                    currentProgress += lastProgress;
                    pb.setProgress(currentProgress);
                    handler.sendEmptyMessage(1);
                    fis.close();
                }

                System.out.println("執行緒" + threadId + " 的下載區間是:"
                        + startIndex + " --- " + endIndex);

                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                conn.setReadTimeout(5000);
                // 關鍵:宣告本次只要這個區間的資料
                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");
                    // 這就是為何要用 RandomAccessFile:seek 能直接定位寫入點
                    raf.seek(startIndex);

                    while ((len = is.read(b)) != -1) {
                        raf.write(b, 0, len);
                        total += len;

                        currentProgress += len;
                        pb.setProgress(currentProgress);
                        handler.sendEmptyMessage(1);

                        // 同步把本執行緒的進度落盤
                        RandomAccessFile progressRaf =
                                new RandomAccessFile(progressFile, "rwd");
                        progressRaf.write((total + "").getBytes());
                        progressRaf.close();
                    }

                    System.out.println("執行緒" + threadId + " 下載完畢");
                    raf.close();

                    finishedThread++;
                    synchronized (path) {
                        if (finishedThread == ThreadCount) {
                            // 全部完成,清掉進度檔
                            for (int i = 0; i < ThreadCount; i++) {
                                File f = new File(
                                        Environment.getExternalStorageDirectory(), i + ".txt");
                                f.delete();
                            }
                            finishedThread = 0;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

activity_main.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="開始下載" />

    <ProgressBar
        android:id="@+id/pb"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleHorizontal" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

幾個容易踩到的坑

權限別忘了加。需要 android.permission.INTERNET 與 android.permission.WRITE_EXTERNAL_STORAGE(Android 6.0 以上還要動態請求)。

伺服器必須支援 Range。回應標頭要帶 Accept-Ranges: bytes,狀態碼要是 206。若伺服器忽略 Range 直接回 200,程式會拿到整份檔案寫到錯誤的位置,檔案就壞了。正式上線前務必確認 CDN 與後端都支援。

進度條的整數溢位。範例中已用 (long) 轉型處理。檔案超過十幾 MB 時,int 相乘就會溢位變負數,這是常見的初學者陷阱。

執行緒安全的計數。finishedThread++ 並非原子操作,範例用 synchronized (path) 保護。更嚴謹的做法是用 AtomicInteger 或 CountDownLatch。

寫檔頻率太高。範例中每讀 1KB 就開關一次進度檔,I/O 開銷非常大。實務上應該間隔固定時間(例如每秒一次)或固定位元組數才落盤,兼顧續傳精度與效能。

別忘了斷點續傳需要伺服器回傳檔案總長度。第一次請求時要讀 Content-Length;若伺服器用了 chunked encoding 而不回傳這個標頭,就得改用其他方式取得大小。

可直接沿用的成熟方案

除非是公司要求自己造輪子,否則建議直接使用成熟函式庫:Android 系統內建的 DownloadManager(免費、支援通知列與自動續傳,但客製化空間有限),或社群方案如 FileDownloader、OkDownload。它們在重試策略、雜湊校驗、資料庫化的任務管理上都做得比手刻版本完整得多。上面這份程式碼的價值,主要在於幫助你理解 Range 請求與隨機寫入背後的原理。

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