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

Android 多執行緒下載流程深度剖析

編輯:關於 Android 程式設計

多執行緒下載檔案的核心思路,是把一個大檔案切成若干片段,交由多條執行緒平行抓取,最後再合併寫入同一個檔案。整個流程可以拆解為以下幾個關鍵步驟:

(1)取得檔案長度並預先配置本地檔案空間

先透過 HttpURLConnection.getContentLength() 取得遠端檔案的總長度,再用 RandomAccessFile 建立一個大小相同的本地檔案:

HttpURLConnection.getContentLength(); // 取得下載檔案的長度
RandomAccessFile file = new RandomAccessFile("QQSetup.exe", "rwd");
file.setLength(filesize); // 設定本地檔案的長度

(2)依檔案長度與執行緒數計算每條執行緒的分工

例如檔案長度為 6M、執行緒數為 3,那麼每條執行緒負責下載 2M,各自的起訖位置如下圖所示:

以 10M 的檔案、3 條執行緒為例:每條執行緒下載的長度為(10 % 3 == 0 ? 10/3 : 10/3 + 1),因此第 1、2 條執行緒各下載 4M,第 3 條下載 2M。

下載起始位置:執行緒 id × 每條執行緒的資料長度

下載結束位置:(執行緒 id + 1)× 每條執行緒的資料長度 − 1

(3)透過 HTTP 的 Range 標頭指定每條執行緒的下載範圍

例如指定從檔案 2M 處開始,下載到 (4M − 1 byte) 為止:

HttpURLConnection.setRequestProperty("Range", "bytes=2097152-4194303");

(4)使用 RandomAccessFile 指定各執行緒寫入本地檔案的起始位置

RandomAccessFile threadFile = new RandomAccessFile("QQWubiSetup.exe", "rwd");
threadFile.seek(2097152); // 指定從檔案的哪個位置開始寫入資料

以下是一個負責更新 UI 的多執行緒下載類別範例:

/**
 * 多執行緒下載,UI 更新類別
 */
public class MultiThreadDownload extends Thread {
    private static final String TAG = "MultiThreadDownload";
    /** 每一條執行緒需要下載的大小 */
    private int blockSize;
    /** 執行緒數量,預設為 5 條 */
    private int threadNum = 5;
    /** 檔案大小 */
    private int fileSize;
    /** 已經下載多少 */
    private int downloadSize;
    /** 檔案的 url、執行緒編號、檔名 */
    private String UrlStr, ThreadNo, fileName;
    /** 儲存的路徑 */
    private String savePath;
    /** 下載的百分比 */
    private int downloadPercent = 0;
    /** 平均下載速度 */
    private int downloadSpeed = 0;
    /** 下載所花的時間 */
    private int usedTime = 0;
    /** 目前時間 */
    private long curTime;
    /** 是否已下載完成 */
    private boolean completed = false;
    private Handler handler;

    public MultiThreadDownload(Handler handler, String url, String savePath) {
        this.handler = handler;
        this.UrlStr = url;
        this.savePath = savePath;
    }

    @Override
    public void run() {
        FileDownloadThread[] fds = new FileDownloadThread[threadNum];
        try {
            URL url = new URL(UrlStr);
            URLConnection conn = url.openConnection();
            fileSize = conn.getContentLength();
            this.fileName = FileUtil.getFileName(UrlStr);
            File saveFile = new File(savePath + "/" + fileName);
            RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
            // 將本地檔案長度設為與下載檔案相同
            accessFile.setLength(fileSize);
            accessFile.close();
            sendMsg(FileUtil.startDownloadMeg);
            // 計算每條執行緒的資料區塊大小
            blockSize = ((fileSize % threadNum) == 0) ? (fileSize / threadNum) : (fileSize / threadNum + 1);
            for (int i = 0; i < threadNum; i++) {
                int curThreadEndPosition = (i + 1) != threadNum ? ((i + 1) * blockSize - 1) : fileSize;
                FileDownloadThread fdt = new FileDownloadThread(url, saveFile, i * blockSize, curThreadEndPosition);
                fdt.setName("thread" + i);
                fdt.start();
                fds[i] = fdt;
            }
            // 輪詢各執行緒進度並更新 UI,直到全部完成
            boolean finished = false;
            long startTime = System.currentTimeMillis();
            while (!finished) {
                downloadSize = 0;
                finished = true;
                for (int i = 0; i < fds.length; i++) {
                    downloadSize += fds[i].getDownloadSize();
                    if (!fds[i].isFinished()) {
                        finished = false;
                    }
                }
                downloadPercent = (downloadSize * 100) / fileSize;
                curTime = System.currentTimeMillis();
                usedTime = (int) ((curTime - startTime) / 1000);
                if (usedTime == 0) usedTime = 1;
                downloadSpeed = (downloadSize / usedTime) / 1024;
                sleep(1000); // 每秒刷新一次介面
                sendMsg(FileUtil.updateDownloadMeg);
            }
            completed = true;
            sendMsg(FileUtil.endDownloadMeg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.run();
    }

    private void sendMsg(int what) {
        Message msg = new Message();
        msg.what = what;
        handler.sendMessage(msg);
    }
    // 省略部分 getter 與 setter 方法
}

負責實際分塊下載的執行緒類別如下:

public class FileDownloadThread extends Thread {
    private static final String TAG = "FileDownloadThread";
    /** 緩衝區大小 */
    private static final int BUFF_SIZE = 1024;
    private URL url;
    private File file;
    /** 起始位置 */
    private int startPosition;
    /** 結束位置 */
    private int endPosition;
    /** 目前位置 */
    private int curPosition;
    /** 是否完成 */
    private boolean finished = false;
    /** 已經下載多少 */
    private int downloadSize = 0;

    public FileDownloadThread(URL url, File file, int startPosition, int endPosition) {
        this.url = url;
        this.file = file;
        this.startPosition = startPosition;
        this.curPosition = startPosition;
        this.endPosition = endPosition;
    }

    @Override
    public void run() {
        BufferedInputStream bis = null;
        RandomAccessFile rAccessFile = null;
        byte[] buf = new byte[BUFF_SIZE];
        try {
            URLConnection conn = url.openConnection();
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            conn.setAllowUserInteraction(true);
            // 透過 Range 標頭指定下載範圍
            conn.setRequestProperty("Range", "bytes=" + startPosition + "-" + endPosition);
            rAccessFile = new RandomAccessFile(file, "rwd");
            // 指定從哪個位置開始寫入
            rAccessFile.seek(startPosition);
            bis = new BufferedInputStream(conn.getInputStream(), BUFF_SIZE);
            int len = 0;
            while (curPosition < endPosition && (len = bis.read(buf, 0, BUFF_SIZE)) != -1) {
                curPosition += len;
                if (curPosition > endPosition) {
                    // 若下載超出範圍,則扣除多餘部分
                    int extraLen = curPosition - endPosition;
                    downloadSize += (len - extraLen + 1);
                } else {
                    downloadSize += len;
                }
            }
            this.finished = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            FileUtil.closeInputStream(bis);
            try {
                rAccessFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        super.run();
    }

    public boolean isFinished() {
        return finished;
    }

    public int getDownloadSize() {
        return downloadSize;
    }
}

總結來說,多執行緒下載屬於分段下載:僅建立並保存一個檔案,各子執行緒透過 RandomAccessFile 類別,把資料寫入到對應的偏移位置,藉此實現平行下載。

示例原始碼:demo 下載。

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