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

Android 多執行緒下載完整實作:分段、斷點續傳與進度條

編輯:關於 Android 程式設計

單執行緒下載一個幾十 MB 的檔案,使用者盯著 0% 看實在煎熬。多執行緒下載的價值有兩個:把頻寬吃得更滿,以及斷線之後能從上次的位置接著跑。做法是先用 HTTP 的 Range 標頭把檔案切成好幾段,每個執行緒各寫自己那一段。

核心觀念

整個機制靠三個零件支撐:HttpURLConnection 搭配 Range: bytes=start-end 要求伺服器只回傳某個區間;RandomAccessFile 讓多個執行緒可以對「同一個檔案」的不同位移各自寫入而不互相覆蓋;以及把每個執行緒已下載的長度寫到一個小檔案裡,重來時讀回來當作起點,這就是斷點續傳。

下載流程(MainActivity)

public void downLoad(View v) {
    MainActivity.flag = true;
    MainActivity.pb_count = 0;
    path = et_url.getText().toString();
    String threadNum_et = et_num.getText().toString();

    if (TextUtils.isEmpty(path) || TextUtils.isEmpty(threadNum_et)) {
        Toast.makeText(this, "不能為空", Toast.LENGTH_LONG).show();
        return;
    }
    threadNum = Integer.valueOf(threadNum_et);

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                conn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)");

                if (conn.getResponseCode() == 200) {
                    size = conn.getContentLength();
                    pb_thread.setMax(size);

                    if (Environment.getExternalStorageState().equals(
                            Environment.MEDIA_MOUNTED)) {
                        File sdFile = Environment.getExternalStorageDirectory();
                        File file = new File(sdFile, "youdao.exe");
                        RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
                        accessFile.setLength(size);        // 先預留完整大小

                        blockSize = size / threadNum;      // 每段的大小
                        for (int i = 1; i <= threadNum; i++) {
                            int startSize = (i - 1) * blockSize;
                            int endSize = i * blockSize;
                            if (i == threadNum && size > endSize) {
                                endSize = size;            // 最後一段吃掉餘數
                            }
                            RandomAccessFile threadAccessFile =
                                new RandomAccessFile(file, "rwd");
                            new Thread(new DownLoadThread(i, threadAccessFile,
                                    startSize, endSize, path)).start();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}

// 暫停:把旗標設為 false,各執行緒下一輪迴圈就會自行退出
public void downPause(View v) {
    Toast.makeText(this, "暫停", Toast.LENGTH_LONG).show();
    this.flag = false;
}

每個執行緒要做的事(DownLoadThread)

public class DownLoadThread implements Runnable {

    public RandomAccessFile accessFile;
    public int startSize;
    public int endSize;
    public String path;
    public int threadId;

    public DownLoadThread(int threadId, RandomAccessFile accessFile,
                          int startSize, int endSize, String path) {
        this.threadId = threadId;
        this.accessFile = accessFile;
        this.startSize = startSize;
        this.endSize = endSize;
        this.path = path;
    }

    @Override
    public void run() {
        try {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                File sdFile = Environment.getExternalStorageDirectory();
                File threadFile = new File(sdFile, threadId + ".txt");

                // 讀回上次的進度,實現斷點續傳
                if (threadFile.exists()) {
                    byte[] data = StreamTools.isToData(new FileInputStream(threadFile));
                    String threadLen = new String(data);
                    if (threadLen != null && !"".equals(threadLen)) {
                        startSize = Integer.valueOf(threadLen);
                        if (startSize > endSize) {
                            startSize = endSize - 1;   // 避開 416 錯誤
                        }
                    }
                }

                HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                conn.setRequestProperty("Range", "bytes=" + startSize + "-" + endSize);

                accessFile.seek(startSize);            // 關鍵:定位到該段起點
                InputStream is = conn.getInputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                int threadTotal = 0;

                while ((len = is.read(buffer)) != -1) {
                    accessFile.write(buffer, 0, len);
                    threadTotal += len;
                    setProgressBar(len);

                    // 把已下載長度寫進小檔案,供下次續傳
                    FileOutputStream fos = new FileOutputStream(threadFile);
                    fos.write((threadTotal + "").getBytes());
                    fos.flush();
                    fos.close();

                    MainActivity.handler.sendEmptyMessage(MainActivity.TEXTVALUE);
                    if (!MainActivity.flag) {
                        return;                        // 收到暫停指令
                    }
                }
                accessFile.close();
                is.close();

                synchronized (MainActivity.class) {
                    MainActivity.threadCount++;
                    if (MainActivity.threadCount >= MainActivity.threadNum) {
                        for (int i = 1; i <= MainActivity.threadNum; i++) {
                            File deleteFile = new File(sdFile, i + ".txt");
                            if (deleteFile.exists()) {
                                deleteFile.delete();   // 全部完成後清掉進度檔
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public synchronized void setProgressBar(int len) {
        MainActivity.pb_count += len;
        MainActivity.pb_thread.setProgress(MainActivity.pb_count);
    }
}

輔助工具類(StreamTools)

public class StreamTools {
    public static byte[] isToData(InputStream is) throws IOException {
        ByteArrayOutputStream bops = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = is.read(buffer)) != -1) {
            bops.write(buffer, 0, len);
        }
        byte[] data = bops.toByteArray();
        bops.flush();
        bops.close();
        is.close();
        return data;
    }
}

幾個實務上會撞到的細節

為什麼要判斷 startSize > endSize 並回退一格?因為檔案已經下載完畢時,續傳的起點會等於甚至超過終點,伺服器收到不合法的 Range 會回 416 Requested Range Not Satisfiable,下載就卡死了。

進度條為什麼要用 Handler?因為 Android 只允許在建立 View 的那條執行緒上更新 UI。這裡的做法是各下載執行緒把長度累加到共用的計數器,再送空訊息給 Handler,由 Handler 在 UI 執行緒上把百分比寫進 TextView。順帶一提,範例中 pb_count += len 與 setProgress 之間的同步是靠 synchronized 保住計數正確,但 setProgress 本身仍應回到 UI 執行緒呼叫才嚴謹。

最後,這套程式有幾個時代痕跡值得注意:外部儲存權限在 Android 6.0 之後需要執行期動態申請,Android 10 更導入 Scoped Storage,直接寫 Environment.getExternalStorageDirectory() 已不再是建議做法;清除暫停旗標也只是讓執行緒自己退出,並未真正釋放連線。若要重用它,把「檔案落地」換成 app 私有目錄或 MediaStore,下載核心則可考慮 WorkManager 搭配 OkHttp。

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