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

Android 斷點下載實作詳解(二):Control 層與 FileDownloader

編輯:關於 Android 程式設計

由於一篇部落格難以完整呈現,本篇承接上一篇,接著實作 MVC 中的 Control 層——在背景利用多執行緒完成斷點下載。

FileDownloader 源碼

import java.io.File;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import android.content.Context;

public class FileDownloader {
    private static final String TAG = "FileDownloader";

    private Context context;
    private FileService fileService;
    private boolean exit;
    private int downloadSize = 0;
    private int fileSize = 0;
    private DownloadThread[] threads;
    private File saveFile;

    /** 快取各執行緒下載的長度 */
    private Map<Integer, Integer> data = new ConcurrentHashMap<Integer, Integer>();

    private int block;      // 每條執行緒下載的長度
    private String downloadUrl;

    public int getThreadSize() {
        return threads.length;
    }

    public void exit() {
        this.exit = true;
    }

    public boolean getExit() {
        return this.exit;
    }

    public int getFileSize() {
        return fileSize;
    }

    /** 累計已下載大小 */
    protected synchronized void append(int size) {
        downloadSize += size;
    }

    /** 更新指定執行緒最後下載的位置 */
    protected synchronized void update(int threadId, int pos) {
        this.data.put(threadId, pos);
        this.fileService.update(this.downloadUrl, threadId, pos);
    }

    public FileDownloader(Context context, String downloadUrl,
                          File fileSaveDir, int threadNum) {
        try {
            this.context = context;
            this.downloadUrl = downloadUrl;
            fileService = new FileService(this.context);
            URL url = new URL(this.downloadUrl);
            if (!fileSaveDir.exists()) fileSaveDir.mkdirs();
            this.threads = new DownloadThread[threadNum];
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5 * 1000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            if (conn.getResponseCode() == 200) {
                this.fileSize = conn.getContentLength();
                if (this.fileSize <= 0) throw new RuntimeException("Unknown file size");
                String filename = getFileName(conn);
                this.saveFile = new File(fileSaveDir, filename);
                Map<Integer, Integer> logdata = fileService.getData(downloadUrl);
                if (logdata.size() > 0) {
                    // 若存在下載記錄,則將各執行緒已下載長度放入 data
                    for (Map.Entry<Integer, Integer> entry : logdata.entrySet()) {
                        data.put(entry.getKey(), entry.getValue());
                    }
                }
                if (this.data.size() == this.threads.length) {
                    for (int i = 0; i < this.threads.length; i++) {
                        this.downloadSize += this.data.get(i + 1);
                    }
                }
                // 計算每條執行緒下載的長度
                this.block = (this.fileSize % this.threads.length) == 0
                        ? this.fileSize / this.threads.length
                        : this.fileSize / this.threads.length + 1;
            } else {
                throw new RuntimeException("server no response");
            }
        } catch (Exception e) {
            throw new RuntimeException("don't connection this url");
        }
    }

    /** 取得檔名 */
    private String getFileName(HttpURLConnection conn) {
        String filename = this.downloadUrl.substring(
                this.downloadUrl.lastIndexOf('/') + 1);
        if (filename == null || "".equals(filename.trim())) {
            filename = UUID.randomUUID() + ".tmp";
        }
        return filename;
    }

    /** 開始下載 */
    public int download(DownloadProgressListener listener) throws Exception {
        try {
            RandomAccessFile randOut = new RandomAccessFile(this.saveFile, "rw");
            if (this.fileSize > 0) randOut.setLength(this.fileSize);
            randOut.close();
            URL url = new URL(this.downloadUrl);
            if (this.data.size() != this.threads.length) {
                this.data.clear();
                for (int i = 0; i < this.threads.length; i++) {
                    this.data.put(i + 1, 0);
                }
                this.downloadSize = 0;
            }
            for (int i = 0; i < this.threads.length; i++) {
                int downLength = this.data.get(i + 1);
                if (downLength < this.block && this.downloadSize < this.fileSize) {
                    this.threads[i] = new DownloadThread(this, url, this.saveFile,
                            this.block, this.data.get(i + 1), i + 1);
                    this.threads[i].setPriority(7);
                    this.threads[i].start();
                } else {
                    this.threads[i] = null;
                }
            }
            fileService.delete(this.downloadUrl);
            fileService.save(this.downloadUrl, this.data);
            boolean notFinish = true;
            while (notFinish) {
                Thread.sleep(900);
                notFinish = false;
                for (int i = 0; i < this.threads.length; i++) {
                    if (this.threads[i] != null && !this.threads[i].isFinish()) {
                        notFinish = true;
                        if (this.threads[i].getDownLength() == -1) {
                            this.threads[i] = new DownloadThread(this, url,
                                    this.saveFile, this.block, this.data.get(i + 1), i + 1);
                            this.threads[i].setPriority(7);
                            this.threads[i].start();
                        }
                    }
                }
                if (listener != null) listener.onDownloadSize(this.downloadSize);
            }
            if (downloadSize == this.fileSize) fileService.delete(this.downloadUrl);
        } catch (Exception e) {
            throw new Exception("file download error");
        }
        return this.downloadSize;
    }
}

關鍵程式碼分析

其中 Map<Integer, Integer> data 這個參數的作用,是每次從資料庫讀取各執行緒停止下載時的數值;下載完成後則會刪除該記錄。這正是斷點續傳得以運作的關鍵。

檔案下載位置存放在 SD 卡根目錄,SD 卡路徑作為參數傳入 FileDownloader,並以 URL 中最後 '/' 之後的字串作為檔名;若檔名不存在,則採用伺服器提供的預設名稱(參見 getFileName 方法)。

在 MainActivity 中呼叫 download 方法時開啟了三條執行緒。每次下載前都會從資料庫讀取對應執行緒已下載的長度,並與其應下載的長度比對:若已完成則跳過,否則續傳。程式碼中的迴圈每隔 900 毫秒檢測一次下載是否完成、是否失敗,並將最新進度回傳給 UI 執行緒。這個 sleep 時間可依檔案大小調整——較大的檔案可拉長間隔,較小的檔案則可縮短以加快更新,在效能與使用者體驗之間取得平衡。

值得一提的是,FileDownloader 實際上是控制下載流程的類別,真正執行下載的是 DownloadThread,下一篇將與大家分享它的實作。

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