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

Android 多執行緒斷點續傳下載:原理拆解與完整程式碼實作

編輯:關於 Android 開發

為什麼要多執行緒

多執行緒下載的核心概念:把同一個網路檔案依執行緒數量切成等份,每條執行緒各下載自己那一段,完成後再按原始順序「拼接」成完整檔案。因為多條連線同時傳輸,整體下載效率明顯優於單執行緒,這在檔案下載場景幾乎是必備環節。

實作步驟

一、取得伺服器上目標檔案的大小
這一步需要發一次網路請求,重點只是拿到檔案總長度,作為後續分配下載任務的依據。

二、在本機建立同大小的檔案
用 RandomAccessFile 建立一個與目標檔案等長的檔案。這個 API 支援任意位置的讀寫,正是多執行緒分頭寫入所必需的:每條執行緒只要在自己的起始與結束位移之間寫資料即可。

三、計算每條執行緒的起止位置
可以把原始檔案想像成一個位元組陣列。已知總長度後,每條執行緒要下載的位元組數 blockSize = totalSize / threadCount。若執行緒依 0、1、2…n 編號,則第 n 條的範圍為:

起始位移 startIndex = n * blockSize
結束位移 endIndex   = (n + 1) * blockSize - 1

由於 totalSize 不一定能被 threadCount 整除,最後一條執行緒要特別處理:起始公式不變,結束位移直接設為 totalSize - 1,把餘數吸收掉。

四、開啟多條子執行緒開始下載
在子執行緒中讀流,把 conn.getInputStream() 的內容寫進 RandomAccessFile 對應的區段。

五、記錄下載進度
為每條執行緒配一個臨時檔,用來記錄它目前下載到第幾個位元組。每寫入一段資料就更新一次,這樣即使任務異常中斷,下次也能接續上次的進度,而不是從零重來。

六、刪除臨時檔
所有執行緒都完成後,由最後一條完成的執行緒負責清掉全部臨時檔。

進度條怎麼做

介面上讓使用者輸入檔案網址與執行緒數量,按下確定開始下載,並依執行緒數量動態產生等量的 ProgressBar。ProgressBar 有兩種樣式:圓形(系統預設,無法顯示具體進度,適合不確定要等多久的場合)與長條形(有兩種顏色,高亮部分代表完成進度)。

在我們的情境裡,總量(要下載的位元組數)與已完成量(已下載的位元組數)都是明確的,因此長條形最合適。由於需要動態新增,可以先在版面檔中把樣式寫好,執行時再 inflate 進來。常用 API:

ProgressBar.setMax(int max);        // 設定最大刻度
ProgressBar.setProgress(int progress); // 設定當前進度

值得一提的是,設定最大值與修改進度都可以直接在子執行緒中操作,元件內部已經處理過了,不必再透過 Handler 發 Message 回主執行緒。

版面配置

三條進度條分別對應三條子執行緒:

<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" >

    <EditText
        android:id="@+id/et_path"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入要下載的文件資源路徑"
        android:text="https://192.168.1.104:8080/gg.exe" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="download"
        android:text="下載" />

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

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

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

核心邏輯實作

public class MainActivity extends Activity {

    private EditText et_path;
    private ProgressBar pb0, pb1, pb2;

    /** 開啟幾條執行緒從伺服器下載資料 */
    public static int threadCount = 3;
    public static int runningThreadCount;
    private String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_path = (EditText) findViewById(R.id.et_path);
        pb0 = (ProgressBar) findViewById(R.id.pb0);
        pb1 = (ProgressBar) findViewById(R.id.pb1);
        pb2 = (ProgressBar) findViewById(R.id.pb2);
    }

    // 下載按鈕的點擊事件
    public void download(View view) {
        path = et_path.getText().toString().trim();
        if (TextUtils.isEmpty(path) || (!path.startsWith("https://"))) {
            Toast.makeText(this, "對不起路徑不合法", 0).show();
            return;
        }
        new Thread() {
            public void run() {
                try {
                    // 1. 取得伺服器上目標檔案的大小
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.setRequestMethod("GET");
                    if (conn.getResponseCode() == 200) {
                        int length = conn.getContentLength();
                        System.out.println("伺服器檔案的長度為:" + length);

                        // 2. 在本機建立同大小的檔案
                        RandomAccessFile raf = new RandomAccessFile(
                                Environment.getExternalStorageDirectory().getAbsolutePath()
                                        + "/" + getFileName(path), "rw");
                        raf.setLength(length);
                        raf.close();

                        // 3. 計算每條執行緒下載的起止位置
                        int blocksize = length / threadCount;
                        runningThreadCount = threadCount;
                        for (int threadId = 0; threadId < threadCount; threadId++) {
                            int startIndex = threadId * blocksize;
                            int endIndex = (threadId + 1) * blocksize - 1;
                            if (threadId == (threadCount - 1)) {
                                endIndex = length - 1;
                            }
                            // 4. 開啟子執行緒開始下載
                            new DownloadThread(threadId, startIndex, endIndex).start();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private class DownloadThread extends Thread {
        private int threadId;        // 執行緒 id
        private int startIndex;      // 理論起始位置
        private int endIndex;        // 結束位置
        private int currentPosition; // 目前下載到哪個位置

        public DownloadThread(int threadId, int startIndex, int endIndex) {
            this.threadId = threadId;
            this.startIndex = startIndex;
            this.endIndex = endIndex;
            System.out.println(threadId + "號執行緒下載的範圍為:"
                    + startIndex + " ~~ " + endIndex);
            currentPosition = startIndex;
        }

        @Override
        public void run() {
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                // 檢查本執行緒是否已下載過一部分
                File info = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/" + threadId + ".position");
                RandomAccessFile raf = new RandomAccessFile(
                        Environment.getExternalStorageDirectory().getAbsolutePath()
                                + "/" + getFileName(path), "rw");

                if (info.exists() && info.length() > 0) {
                    FileInputStream fis = new FileInputStream(info);
                    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                    currentPosition = Integer.valueOf(br.readLine());
                    conn.setRequestProperty("Range",
                            "bytes=" + currentPosition + "-" + endIndex);
                    System.out.println("原有下載進度,從上次終止處續傳 bytes="
                            + currentPosition + "-" + endIndex);
                    fis.close();
                    raf.seek(currentPosition);
                } else {
                    // 告訴伺服器只想下載其中一段
                    conn.setRequestProperty("Range",
                            "bytes=" + startIndex + "-" + endIndex);
                    System.out.println("無下載進度,新的下載 bytes="
                            + startIndex + "-" + endIndex);
                    raf.seek(startIndex);
                }

                InputStream is = conn.getInputStream();
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = is.read(buffer)) != -1) {
                    // 把資料寫進本執行緒負責的區段
                    raf.write(buffer, 0, len);

                    // 5. 記錄下載進度
                    currentPosition += len;
                    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                            + "/" + threadId + ".position");
                    // rwd 模式會立刻落盤,避免資料只停在緩衝區
                    RandomAccessFile fos = new RandomAccessFile(file, "rwd");
                    fos.write(String.valueOf(currentPosition).getBytes());
                    fos.close();

                    // 更新進度條
                    int max = endIndex - startIndex;
                    int progress = currentPosition - startIndex;
                    if (threadId == 0) {
                        pb0.setMax(max); pb0.setProgress(progress);
                    } else if (threadId == 1) {
                        pb1.setMax(max); pb1.setProgress(progress);
                    } else if (threadId == 2) {
                        pb2.setMax(max); pb2.setProgress(progress);
                    }
                }
                raf.close();
                is.close();
                System.out.println("執行緒:" + threadId + "下載完畢了...");

                File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/" + threadId + ".position");
                f.renameTo(new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/" + threadId + ".position.finish"));

                synchronized (MainActivity.class) {
                    runningThreadCount--;
                    // 6. 刪除臨時檔
                    if (runningThreadCount <= 0) {
                        for (int i = 0; i < threadCount; i++) {
                            File ft = new File(
                                    Environment.getExternalStorageDirectory().getAbsolutePath()
                                            + "/" + i + ".position.finish");
                            ft.delete();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /** 從路徑中取出檔名 */
    public String getFileName(String path) {
        int start = path.lastIndexOf("/") + 1;
        return path.substring(start);
    }
}

別忘了權限

這個範例同時用到網路與 sdcard 寫入,兩項權限都要補上:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

用 xUtils 更省事

如果不想自己刻,xUtils 的 HttpUtils 已經把斷點續傳封裝好了。xUtils 是開源的 Android 工具包,主要有四大模組:DbUtils(資料庫操作)、ViewUtils(以註解綁定 UI、資源與事件)、HttpUtils(網路訪問與斷點續傳)、BitmapUtils(圖片處理)。使用方式很簡單:把 jar 檔放進 libs 目錄並加入相依即可。

HttpUtils http = new HttpUtils();

/**
 * 參數1:原檔網路位址
 * 參數2:本機保存路徑
 * 參數3:是否支援斷點續傳
 * 參數4:回呼介面,其中的方法都在主執行緒被呼叫,可直接更新 UI
 */
http.download(path, "/mnt/sdcard/xxx.exe", true, new RequestCallBack<File>() {

    // 下載成功後呼叫一次
    @Override
    public void onSuccess(ResponseInfo<File> arg0) {
        Toast.makeText(MainActivity.this, "下載成功", 0).show();
    }

    /**
     * 每下載一段就呼叫一次
     * 參數1:原檔總位元組數
     * 參數2:已下載位元組數
     * 參數3:是否在上傳(下載時為 false)
     */
    @Override
    public void onLoading(long total, long current, boolean isUploading) {
        pb0.setMax((int) total);
        pb0.setProgress((int) current);
        super.onLoading(total, current, isUploading);
    }

    // 失敗後呼叫一次
    @Override
    public void onFailure(HttpException arg0, String arg1) {
        Toast.makeText(MainActivity.this, "下載失敗" + arg1, 0).show();
    }
});

自己實作的好處是流程完全可控,適合要客製化重試策略或自訂分塊規則的場景;用現成庫則勝在快速上線。可依專案階段取捨。

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