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

Android 多執行緒斷點續傳下載實作

編輯:關於 Android 程式設計

大檔案下載若只用單線程,速度慢且一旦中斷就得從頭來過。多執行緒斷點續傳的原理並不複雜,本文從原理一路寫到 Android 版本的可執行範例。

一、原理拆解

第一步:先在本地開一個與伺服器同大小檔案。

要隨機寫入,必須先知道檔案總長度。透過 HTTP 回應標頭中的 Content-Length 取得大小,再用 RandomAccessFile 建立檔案並呼叫 setLength() 預先配置空間。

第二步:切塊並開多個執行緒。

把總長度除以執行緒數(範例用 3),算出每條執行緒負責的起訖位置,透過請求標頭 Range: bytes=start-end 讓伺服器只回傳該區段。各執行緒用 seek() 把檔案指針移到自己的起點後寫入。

第三步:記錄進度以支援續傳。

每條執行緒配一個 id.txt 檔,持續寫入自己已下載到的位置。下次啟動時讀回這個數字,若它大於原定起點,就從該位置續傳。

二、Java SE 版本

public class TestMutileDownload {

    public static final String path = "https://192.168.1.247:8080/youdao.exe";
    public static int threadcount;

    public static void main(String[] args) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
        conn.setConnectTimeout(5000);

        // 取得伺服器檔案大小
        int len = conn.getContentLength();
        System.out.println("檔案大小為" + len);

        // 在本地建立同大小的檔案
        File file = new File("youdao.exe");
        RandomAccessFile randomfile = new RandomAccessFile(file, "rwd");
        randomfile.setLength(len);

        // 假設只開啟 3 個子執行緒
        int blocksize = len / 3;
        for (int i = 1; i <= 3; i++) {
            threadcount = 0;
            int startsize = (i - 1) * blocksize;
            int endsize = i * blocksize - 1;
            if (i == 3) {
                endsize = len;
            }
            new Thread(new DownLoadTask(i, startsize, endsize)).start();
        }
    }
}

執行緒類別:

class DownLoadTask implements Runnable {

    private int id;
    private int startsize;
    private int endsize;

    public DownLoadTask(int id, int startsize, int endsize) {
        this.id = id;
        this.startsize = startsize;
        this.endsize = endsize;
    }

    @Override
    public void run() {
        try {
            File idfile = new File(id + ".txt");

            // 判斷是否有已下載的位置記錄
            if (idfile.exists()) {
                FileInputStream fis = new FileInputStream(idfile);
                byte[] result = StreamTools.getBytes(fis);
                String numberstr = new String(result);
                if (numberstr != null && !"".equals(numberstr)) {
                    int startposition = Integer.parseInt(numberstr);
                    if (startposition > startsize) {
                        startsize = startposition; // 重新指定下載起點
                    }
                }
            }

            URL url = new URL(TestMutileDownload.path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("User-Agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setConnectTimeout(5000);

            // 指定本執行緒的下载區段
            if (startsize > endsize) {
                startsize = endsize - 1;
            }
            conn.setRequestProperty("Range", "bytes=" + startsize + "-" + endsize);

            InputStream is = conn.getInputStream();
            RandomAccessFile randomfile =
                    new RandomAccessFile(new File("youdao.exe"), "rwd");
            randomfile.seek(startsize);

            byte[] buffer = new byte[1024];
            int len = 0;
            int total = 0;
            while ((len = is.read(buffer)) != -1) {
                randomfile.write(buffer, 0, len);
                total += len;

                // 記錄當前執行緒下載到的位置
                FileOutputStream idfos = new FileOutputStream(idfile);
                idfos.write((startsize + total + "").getBytes());
                idfos.flush();
                idfos.close();
            }
            randomfile.close();
            is.close();

            synchronized (TestMutileDownload.class) {
                TestMutileDownload.threadcount++;
                if (TestMutileDownload.threadcount >= 3) {
                    System.out.println("所有執行緒都執行完畢了");
                    for (int i = 1; i <= 3; i++) {
                        File deletefile = new File(i + ".txt");
                        deletefile.delete();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

三、Android 版本差異

搬到 Android 上有三處必須調整:

一是存檔位置改到 Environment.getExternalStorageDirectory(),並在清單檔補上 WRITE_EXTERNAL_STORAGE 權限(Android 6.0 起還要動態申請)。

二是進度條更新必須回到主執行緒。子執行緒只能透過 Handler 發送 Message,由主執行緒的 handleMessage() 更新 ProgressBar,直接從子執行緒操作 View 會導致 CalledFromWrongThreadException。

三是暂停機制。用一個 flag 旗標控制,按下暫停時設為 false,各執行緒在寫入循環中檢查到旗標變 false 就 return 退出;此時 id.txt 已記錄了當前位置,下次點擊下載即可接續。

另外要提醒,範例中每寫入 1KB 就開關一次 id.txt,IO 頻率過高會明顯拖慢速度。實務上宜改為累計到一定門檻(例如 64KB)或每隔數秒才落檔一次。

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