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

Android 多執行緒下載原理剖析

編輯:關於 Android 程式設計

在 Android 開發中,多執行緒操作可謂家常便飯,對它的理解越深,越能讓自己的程式穩定高效地運行。這也是 Android 開發的一個重要知識點,接下來我們就來認識多執行緒下載的原理。

多執行緒下載的步驟大致如下:

1. 在本地建立一個與伺服器檔案大小一致的臨時檔案;

2. 計算分配幾個執行緒,各自負責下載伺服器資源的哪一段;

3. 啟動執行緒,每個執行緒下載對應的檔案片段;

4. 當所有執行緒都完成各自的部分,整個檔案便下載完畢。

如圖所示(假設有三個執行緒同時下載):

import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class DemoLoader {
    private static DemoLoader loader = new DemoLoader();
    private static int threadCount = 3;

    private DemoLoader() { }

    // 單例獲取
    public static DemoLoader getInstance() {
        return loader;
    }

    public void downFile(String path) {
        try {
            URL url = new URL(path);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            connection.setReadTimeout(5000);
            int code = connection.getResponseCode();
            if (code == 200) {
                // 獲取服務器端檔案的長度
                int fileLength = connection.getContentLength();
                // 本地建立一個跟服務器一樣大小的檔案
                RandomAccessFile raf = new RandomAccessFile("setup.ext", "rwd");
                raf.setLength(fileLength);
                raf.close();
                // 假設三個執行緒下載
                int blockSize = fileLength / threadCount;
                for (int threadId = 0; threadId < threadCount; threadId++) {
                    int startIndex = threadId * blockSize;
                    int endIndex = (threadId + 1) * blockSize - 1;
                    if (threadId == threadCount - 1) {
                        endIndex = fileLength - 1;
                    }
                    System.out.println("線程:" + threadId + ",下載:" + startIndex + "--->" + endIndex);
                    // 開始下載
                    new DownLoadThread(threadId, startIndex, endIndex, path).start();
                }
                System.out.println("檔案總長度為:" + fileLength);
            } else {
                System.out.println("請求失敗!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** 下載檔案的執行緒 */
    public class DownLoadThread extends Thread {
        private int threadId;
        private int startIndex;
        private int endIndex;
        private String path;

        /**
         * @param threadId   線程 id
         * @param startIndex 線程下載開始位置
         * @param endIndex   線程下載結束位置
         * @param path       下載位址
         */
        public DownLoadThread(int threadId, int startIndex, int endIndex, String path) {
            this.threadId = threadId;
            this.startIndex = startIndex;
            this.endIndex = endIndex;
            this.path = path;
        }

        @Override
        public void run() {
            super.run();
            try {
                URL url = new URL(path);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                // 請求服務器下載部分的檔案,指定開始位置與結束位置
                connection.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
                connection.setDoInput(true);
                connection.setRequestMethod("GET");
                connection.setReadTimeout(5000);
                // 從服務器獲取全部資料返回 200,獲取部分資料返回 206
                int code = connection.getResponseCode();
                System.out.println("code = " + code);
                InputStream is = connection.getInputStream();
                RandomAccessFile raf = new RandomAccessFile("setup.exe", "rwd");
                // 隨機寫檔案時,從哪裡開始
                raf.seek(startIndex);
                int len = 0;
                byte[] buff = new byte[1024];
                while ((len = is.read(buff)) != -1) {
                    raf.write(buff, 0, len);
                }
                is.close();
                raf.close();
                System.out.println("線程:" + threadId + ",下載完成");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

使用時只需知道一個 url,調用 downFile() 方法便會開始下載。這個思路可以用來下載安裝包,例如從網上下載 QQ、微信等的 APK,再安裝到裝置上,正是同樣的原理。

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