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

Android 多執行緒下載實作:仿下載助手與斷點續傳

編輯:關於 Android 程式設計

先釐清一個常見誤會:本文的「多執行緒下載」不是指用多個執行緒共同下載同一個檔案,而是每個執行緒負責一個檔案,透過執行緒池統一調度。範例的互動是:點擊開始下載並顯示進度,完成後變成「安裝」,點擊即可觸發安裝。

一、認識 ThreadPoolExecutor

ThreadPoolExecutor threadpool = new ThreadPoolExecutor(
        corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);

六個參數的意義:

· corePoolSize:閒置時仍保留在池中的執行緒數。
· maximumPoolSize:允許同時存在的最大執行緒數。
· keepAliveTime:超出核心數的閒置執行緒,最多可存活多久。
· unit:上述時間的單位。
· workQueue:存放待執行 Runnable 的佇列。
· handler:當執行緒與佇列容量都耗盡時的拒絕策略。

二、ThreadManager:集中管理執行緒池

依任務性質分流是實務上的關鍵:長耗時(網路)與短耗時(本地 IO / SQL)若共用同一個佇列,短任務會被長任務堵住。

public class ThreadManager {

    public static final String DEFAULT_SINGLE_POOL_NAME = "DEFAULT_SINGLE_POOL_NAME";

    private static ThreadPoolProxy mLongPool = null;
    private static Object mLongLock = new Object();
    private static ThreadPoolProxy mShortPool = null;
    private static Object mShortLock = new Object();
    private static ThreadPoolProxy mDownloadPool = null;
    private static Object mDownloadLock = new Object();
    private static Map<String, ThreadPoolProxy> mMap = new HashMap<String, ThreadPoolProxy>();
    private static Object mSingleLock = new Object();

    /** 下載專用池 */
    public static ThreadPoolProxy getDownloadPool() {
        synchronized (mDownloadLock) {
            if (mDownloadPool == null) {
                mDownloadPool = new ThreadPoolProxy(3, 3, 5L);
            }
            return mDownloadPool;
        }
    }

    /** 長耗時任務池,通常用於網路操作 */
    public static ThreadPoolProxy getLongPool() {
        synchronized (mLongLock) {
            if (mLongPool == null) {
                mLongPool = new ThreadPoolProxy(5, 5, 5L);
            }
            return mLongPool;
        }
    }

    /** 短耗時任務池,通常用於本地 IO / SQL */
    public static ThreadPoolProxy getShortPool() {
        synchronized (mShortLock) {
            if (mShortPool == null) {
                mShortPool = new ThreadPoolProxy(2, 2, 5L);
            }
            return mShortPool;
        }
    }

    /** 單執行緒池,任務依加入順序執行,免去同步開銷 */
    public static ThreadPoolProxy getSinglePool() {
        return getSinglePool(DEFAULT_SINGLE_POOL_NAME);
    }

    public static ThreadPoolProxy getSinglePool(String name) {
        synchronized (mSingleLock) {
            ThreadPoolProxy singlePool = mMap.get(name);
            if (singlePool == null) {
                singlePool = new ThreadPoolProxy(1, 1, 5L);
                mMap.put(name, singlePool);
            }
            return singlePool;
        }
    }

    public static class ThreadPoolProxy {

        private ThreadPoolExecutor mPool;
        private int mCorePoolSize;
        private int mMaximumPoolSize;
        private long mKeepAliveTime;

        private ThreadPoolProxy(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
            mCorePoolSize = corePoolSize;
            mMaximumPoolSize = maximumPoolSize;
            mKeepAliveTime = keepAliveTime;
        }

        /** 執行任務;若執行緒池已關閉則重建 */
        public synchronized void execute(Runnable run) {
            if (run == null) {
                return;
            }
            if (mPool == null || mPool.isShutdown()) {
                mPool = new ThreadPoolExecutor(mCorePoolSize, mMaximumPoolSize,
                        mKeepAliveTime, TimeUnit.MILLISECONDS,
                        new LinkedBlockingQueue<Runnable>(),
                        Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
            }
            mPool.execute(run);
        }

        /** 移除尚未執行的任務 */
        public synchronized void cancel(Runnable run) {
            if (mPool != null && (!mPool.isShutdown() || mPool.isTerminating())) {
                mPool.getQueue().remove(run);
            }
        }

        /** 查詢佇列中是否包含該任務 */
        public synchronized boolean contains(Runnable run) {
            if (mPool != null && (!mPool.isShutdown() || mPool.isTerminating())) {
                return mPool.getQueue().contains(run);
            }
            return false;
        }

        /** 立即關閉,正在執行的任務會被中斷 */
        public void stop() {
            if (mPool != null && (!mPool.isShutdown() || mPool.isTerminating())) {
                mPool.shutdownNow();
            }
        }

        /** 平緩關閉,確保已加入的任務都執行完畢 */
        public synchronized void shutdown() {
            if (mPool != null && (!mPool.isShutdown() || mPool.isTerminating())) {
                mPool.shutdown();
            }
        }
    }
}

三、DownloadTask:真正的下載工作

下載的原理很朴素:從 URL 取得輸入串流,逐段寫入本機檔案。因為下載發生在 run() 裡,關鍵就是這一段:

fos = new FileOutputStream(file, true);
int count = -1;
byte[] buffer = new byte[1024];
while (((count = stream.read(buffer)) != -1) && info.getDownloadState() == STATE_DOWNLOADING) {
    // 每次讀到資料都要確認狀態,非下載中則中止
    fos.write(buffer, 0, count);
    fos.flush();
    info.setCurrentSize(info.getCurrentSize() + count);
    notifyDownloadProgressed(info);   // 刷新進度
}

完整的 DownloadTask:

/** 下載任務 */
public class DownloadTask implements Runnable {

    private DownloadInfo info;

    public DownloadTask(DownloadInfo info) {
        this.info = info;
    }

    @Override
    public void run() {
        info.setDownloadState(STATE_DOWNLOADING);
        notifyDownloadStateChanged(info);

        File file = new File(info.getPath());
        HttpResult httpResult = null;
        InputStream stream = null;

        // 檔案不存在、進度為 0,或進度與檔案長度不符,就重新下載
        if (info.getCurrentSize() == 0 || !file.exists() || file.length() != info.getCurrentSize()) {
            info.setCurrentSize(0);
            file.delete();
        }

        httpResult = HttpHelper.download(info.getUrl());

        if (httpResult == null || (stream = httpResult.getInputStream()) == null) {
            info.setDownloadState(STATE_ERROR);
            notifyDownloadStateChanged(info);
        } else {
            try {
                skipBytesFromStream(stream, info.getCurrentSize());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(file, true);
                int count = -1;
                byte[] buffer = new byte[1024];
                while (((count = stream.read(buffer)) != -1)
                        && info.getDownloadState() == STATE_DOWNLOADING) {
                    fos.write(buffer, 0, count);
                    fos.flush();
                    info.setCurrentSize(info.getCurrentSize() + count);
                    notifyDownloadProgressed(info);
                }
            } catch (Exception e) {
                info.setDownloadState(STATE_ERROR);
                notifyDownloadStateChanged(info);
                info.setCurrentSize(0);
                file.delete();
            } finally {
                IOUtils.close(fos);
                if (httpResult != null) {
                    httpResult.close();
                }
            }

            if (info.getCurrentSize() == info.getAppSize()) {
                info.setDownloadState(STATE_DOWNLOADED);
                notifyDownloadStateChanged(info);
            } else if (info.getDownloadState() == STATE_PAUSED) {
                notifyDownloadStateChanged(info);
            } else {
                info.setDownloadState(STATE_ERROR);
                notifyDownloadStateChanged(info);
                info.setCurrentSize(0);
                file.delete();
            }
        }
        mTaskMap.remove(info.getId());
    }
}

四、用觀察者模式刷新 UI

按鈕上顯示「下載 / 暫停 / 百分比」,靠的是 notifyDownloadProgressed() 與 notifyDownloadStateChanged() 兩個方法,而它們本質上是遍歷一份觀察者清單:

public interface DownloadObserver {
    void onDownloadStateChanged(DownloadInfo info);
    void onDownloadProgressed(DownloadInfo info);
}

/** 下載狀態改變時回呼 */
public void notifyDownloadStateChanged(DownloadInfo info) {
    synchronized (mObservers) {
        for (DownloadObserver observer : mObservers) {
            observer.onDownloadStateChanged(info);
        }
    }
}

/** 下載進度改變時回呼 */
public void notifyDownloadProgressed(DownloadInfo info) {
    synchronized (mObservers) {
        for (DownloadObserver observer : mObservers) {
            observer.onDownloadProgressed(info);
        }
    }
}

/** 註冊觀察者 */
public void registerObserver(DownloadObserver observer) {
    synchronized (mObservers) {
        if (!mObservers.contains(observer)) {
            mObservers.add(observer);
        }
    }
}

/** 反註冊觀察者 */
public void unRegisterObserver(DownloadObserver observer) {
    synchronized (mObservers) {
        if (mObservers.contains(observer)) {
            mObservers.remove(observer);
        }
    }
}

而 UI 更新放在 Adapter 裡——因為每一列的版面配置本來就是在 getView() 中載入的:

public class RecommendAdapter extends BaseAdapter implements DownloadManager.DownloadObserver {

    private ArrayList<AppInfo> list;
    private List<ViewHolder> mDisplayedHolders;

    public void startObserver() {
        DownloadManager.getInstance().registerObserver(this);
    }

    public void stopObserver() {
        DownloadManager.getInstance().unRegisterObserver(this);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        AppInfo appInfo = list.get(position);
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder(context);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.setData(appInfo);
        mDisplayedHolders.add(holder);
        return holder.getRootView();
    }

    @Override
    public void onDownloadStateChanged(DownloadInfo info) {
        refreshHolder(info);
    }

    @Override
    public void onDownloadProgressed(DownloadInfo info) {
        refreshHolder(info);
    }

    /** 只刷新畫面上目前可見的 ViewHolder,避免全表更新 */
    private void refreshHolder(final DownloadInfo info) {
        List<ViewHolder> displayedHolders = getDisplayedHolders();
        for (int i = 0; i < displayedHolders.size(); i++) {
            final ViewHolder holder = displayedHolders.get(i);
            AppInfo appInfo = holder.getData();
            if (appInfo.getId() == info.getId()) {
                AppUtil.post(new Runnable() {
                    @Override
                    public void run() {
                        holder.refreshState(info.getDownloadState(), info.getProgress());
                    }
                });
            }
        }
    }

    public class ViewHolder {
        public TextView textView01, textView02, textView03, textView04;
        public ImageView imageView_icon;
        public Button button;
        public LinearLayout linearLayout;
        public AppInfo mData;
        private DownloadManager mDownloadManager;
        private int mState;
        private float mProgress;
        protected View mRootView;

        public ViewHolder(Context context) {
            mRootView = initView();
            mRootView.setTag(this);
        }

        public View getRootView() {
            return mRootView;
        }

        public View initView() {
            View view = AppUtil.inflate(R.layout.item_recommend_award);
            imageView_icon = (ImageView) view.findViewById(R.id.imageview_task_app_cion);
            textView01 = (TextView) view.findViewById(R.id.textview_task_app_name);
            textView02 = (TextView) view.findViewById(R.id.textview_task_app_size);
            textView03 = (TextView) view.findViewById(R.id.textview_task_app_desc);
            textView04 = (TextView) view.findViewById(R.id.textview_task_app_love);
            button = (Button) view.findViewById(R.id.button_task_download);
            linearLayout = (LinearLayout) view.findViewById(R.id.linearlayout_task);

            button.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mState == DownloadManager.STATE_NONE
                            || mState == DownloadManager.STATE_PAUSED
                            || mState == DownloadManager.STATE_ERROR) {
                        mDownloadManager.download(mData);
                    } else if (mState == DownloadManager.STATE_WAITING
                            || mState == DownloadManager.STATE_DOWNLOADING) {
                        mDownloadManager.pause(mData);
                    } else if (mState == DownloadManager.STATE_DOWNLOADED) {
                        mDownloadManager.install(mData);
                    }
                }
            });
            return view;
        }

        public void setData(AppInfo data) {
            if (mDownloadManager == null) {
                mDownloadManager = DownloadManager.getInstance();
            }
            // 若本機已有同檔且大小相符,直接視為下載完成
            String filepath = FileUtil.getDownloadDir(AppUtil.getContext())
                    + File.separator + data.getName() + ".apk";
            if (FileUtil.isExistsFile(filepath)) {
                int fileSize = FileUtil.getFileSize(filepath);
                if (data.getSize() == fileSize) {
                    DownloadInfo downloadInfo = DownloadInfo.clone(data);
                    downloadInfo.setCurrentSize(data.getSize());
                    downloadInfo.setHasFinished(true);
                    mDownloadManager.setDownloadInfo(data.getId(), downloadInfo);
                }
            }
            DownloadInfo downloadInfo = mDownloadManager.getDownloadInfo(data.getId());
            if (downloadInfo != null) {
                mState = downloadInfo.getDownloadState();
                mProgress = downloadInfo.getProgress();
            } else {
                mState = DownloadManager.STATE_NONE;
                mProgress = 0;
            }
            this.mData = data;
            refreshView();
        }

        public AppInfo getData() {
            return mData;
        }

        /** 依狀態切換按鈕文字 */
        public void refreshState(int state, float progress) {
            mState = state;
            mProgress = progress;
            switch (mState) {
                case DownloadManager.STATE_NONE:
                    button.setText(R.string.app_state_download); break;
                case DownloadManager.STATE_PAUSED:
                    button.setText(R.string.app_state_paused); break;
                case DownloadManager.STATE_ERROR:
                    button.setText(R.string.app_state_error); break;
                case DownloadManager.STATE_WAITING:
                    button.setText(R.string.app_state_waiting); break;
                case DownloadManager.STATE_DOWNLOADING:
                    button.setText((int) (mProgress * 100) + "%"); break;
                case DownloadManager.STATE_DOWNLOADED:
                    button.setText(R.string.app_state_downloaded); break;
                default: break;
            }
        }
    }
}

最後在主畫面呼叫 adapter.startObserver(),把實作介面的 Adapter 註冊進容器,資料流就接通了。

五、DownloadManager:狀態機與任務調度

public class DownloadManager {

    public static final int STATE_NONE = 0;       // 未開始
    public static final int STATE_WAITING = 1;    // 等待中
    public static final int STATE_DOWNLOADING = 2;// 下載中
    public static final int STATE_PAUSED = 3;     // 已暫停
    public static final int STATE_DOWNLOADED = 4; // 下載完畢
    public static final int STATE_ERROR = 5;      // 失敗

    private static DownloadManager instance;

    /** 下載資訊,正式專案需持久化 */
    private Map<Long, DownloadInfo> mDownloadMap = new ConcurrentHashMap<Long, DownloadInfo>();
    /** 觀察者清單 */
    private List<DownloadObserver> mObservers = new ArrayList<DownloadObserver>();
    /** 執行中的任務,方便依 id 取消 */
    private Map<Long, DownloadTask> mTaskMap = new ConcurrentHashMap<Long, DownloadTask>();

    public static synchronized DownloadManager getInstance() {
        if (instance == null) {
            instance = new DownloadManager();
        }
        return instance;
    }

    /** 開始下載 */
    public synchronized void download(AppInfo appInfo) {
        DownloadInfo info = mDownloadMap.get(appInfo.getId());
        if (info == null) {
            info = DownloadInfo.clone(appInfo);
            mDownloadMap.put(appInfo.getId(), info);
        }
        // 只有這三種狀態可以啟動下載
        if (info.getDownloadState() == STATE_NONE
                || info.getDownloadState() == STATE_PAUSED
                || info.getDownloadState() == STATE_ERROR) {
            // 先標記為等待中,任務真正開始執行時才會改成 STATE_DOWNLOADING
            info.setDownloadState(STATE_WAITING);
            notifyDownloadStateChanged(info);
            DownloadTask task = new DownloadTask(info);
            mTaskMap.put(info.getId(), task);
            ThreadManager.getDownloadPool().execute(task);
        }
    }

    /** 暫停:保留已下載的檔案 */
    public synchronized void pause(AppInfo appInfo) {
        stopDownload(appInfo);
        DownloadInfo info = mDownloadMap.get(appInfo.getId());
        if (info != null) {
            info.setDownloadState(STATE_PAUSED);
            notifyDownloadStateChanged(info);
        }
    }

    /** 取消:額外刪除已下載的檔案 */
    public synchronized void cancel(AppInfo appInfo) {
        stopDownload(appInfo);
        DownloadInfo info = mDownloadMap.get(appInfo.getId());
        if (info != null) {
            info.setDownloadState(STATE_NONE);
            notifyDownloadStateChanged(info);
            info.setCurrentSize(0);
            File file = new File(info.getPath());
            file.delete();
        }
    }

    /** 觸發安裝 */
    public synchronized void install(AppInfo appInfo) {
        stopDownload(appInfo);
        DownloadInfo info = mDownloadMap.get(appInfo.getId());
        if (info != null) {
            Intent installIntent = new Intent(Intent.ACTION_VIEW);
            installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            installIntent.setDataAndType(Uri.parse("file://" + info.getPath()),
                    "application/vnd.android.package-archive");
            AppUtil.getContext().startActivity(installIntent);
        }
        notifyDownloadStateChanged(info);
    }

    /** 若任務還在池中且尚未執行,先移除 */
    private void stopDownload(AppInfo appInfo) {
        DownloadTask task = mTaskMap.remove(appInfo.getId());
        if (task != null) {
            ThreadManager.getDownloadPool().cancel(task);
        }
    }
}

六、斷點續傳的兩種做法

做法一:由伺服器續傳。暫停時記下已下載的位元組數,繼續時透過 Range 表頭告訴伺服器要從哪裡接著送:

// 檔案存在且長度等於目前進度時,採用 Range 續傳
httpResult = HttpHelper.download(info.getUrl() + "&range=" + info.getCurrentSize());

伺服器端只要取出參數並判斷有無:

String range = req.getParameter("range");

若無 range,就整檔送出:

FileInputStream stream = new FileInputStream(file);
int count = -1;
byte[] buffer = new byte[1024];
while ((count = stream.read(buffer)) != -1) {
    out.write(buffer, 0, count);
    out.flush();
}
stream.close();
out.close();

若有 range,先用 RandomAccessFile.seek() 跳到指定位置再續寫:

RandomAccessFile raf = new RandomAccessFile(file, "r");
raf.seek(Long.valueOf(range));
int count = -1;
byte[] buffer = new byte[1024];
while ((count = raf.read(buffer)) != -1) {
    out.write(buffer, 0, count);
    out.flush();
}
raf.close();
out.close();

做法二:由本機跳過已下載的位元組。這種做法不必改伺服器,但有個嚴重缺陷:InputStream.skip() 並不保證跳過你要的數量,往往只跳過一部分,因此必須反覆迴圈直到滿足條件。檔案越大越慘——若已下載 15MB 才暫停,恢復時要逐段跳過這 15MB,動輒數秒到數十秒。

七、改進版:HttpURLConnection + RandomAccessFile

改進重點有兩個:一是用 Range 表頭讓伺服器直接從斷點續傳,不再依賴 skip();二是本次未完成的下載,下次進 App 可以接著上次的進度繼續,而不是刪檔重來。

@Override
public void run() {
    info.setDownloadState(STATE_DOWNLOADING);
    notifyDownloadStateChanged(info);

    File file = new File(info.getPath());
    try {
        URL url = new URL(info.getUrl());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);

        // 先判斷本機檔案狀態
        if (!file.exists()) {
            info.setCurrentSize(0);
            file.delete();
        } else if (file.length() > info.getAppSize()) {
            info.setCurrentSize(0);
            file.delete();
        } else if (file.length() == info.getAppSize()) {
            // 已完成
        } else if (file.length() < info.getAppSize()) {
            info.setCurrentSize(file.length());
        }

        if (info.getCurrentSize() == 0 || !file.exists()
                || file.length() != info.getCurrentSize()) {
            // 重新下載
            info.setCurrentSize(0);
            file.delete();
        } else if (file.length() == info.getCurrentSize() && file.length() < info.getAppSize()) {
            // 續傳:告訴伺服器要哪一段
            conn.setRequestProperty("Range", "bytes=" + info.getCurrentSize() + "-" + info.getAppSize());
        }

        int code = conn.getResponseCode();
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        InputStream is = conn.getInputStream();
        byte[] buffer = new byte[1024 * 8];
        int len = -1;

        // 200 = 伺服器回傳完整檔案;206 = 部分內容(續傳成功)
        if (code == 200) {
            // 從頭寫
        } else if (code == 206) {
            raf.seek(file.length());   // 跳到既有內容的結尾
        }

        while (((len = is.read(buffer)) != -1) && (info.getDownloadState() == STATE_DOWNLOADING)) {
            raf.write(buffer, 0, len);
            info.setCurrentSize(info.getCurrentSize() + len);
            notifyDownloadProgressed(info);
        }
        is.close();
        raf.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (info.getCurrentSize() == info.getAppSize()) {
        info.setDownloadState(STATE_DOWNLOADED);
        notifyDownloadStateChanged(info);
    } else if (info.getDownloadState() == STATE_PAUSED) {
        notifyDownloadStateChanged(info);
    } else {
        info.setDownloadState(STATE_ERROR);
        notifyDownloadStateChanged(info);
        info.setCurrentSize(0);
        file.delete();
    }
    mTaskMap.remove(info.getId());
}

兩個關鍵點:RandomAccessFile 同時實作 DataInput 與 DataOutput,可讀可寫,用它的 seek() 定位比 InputStream.skip() 可靠得多;而 HTTP 狀態碼 200 與 206 的區別,正是判斷「伺服器有沒有依 Range 續傳」的依據。

還有一點實務上必須補完:若是網路中途斷線(SocketTimeoutException、UnknownHostException),目前流程會落到 STATE_ERROR 並刪檔,但其實更合理的做法是保留已下載的位元組、標記為 STATE_PAUSED,等網路恢復後續傳。這部分可依產品需求自行補上。另外記得在 AndroidManifest 加上 android.permission.INTERNET 與 WRITE_EXTERNAL_STORAGE,並注意 Android 9 之後明文流量需要 usesCleartextTraffic 或改用 HTTPS。

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