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

Android 多線程斷點續傳下載的完整實現(附源碼)

編輯:關於 Android 程式設計

多線程 + 斷點續傳是下載功能的標準答案。它把一個大文件切成若干塊,交給多個線程並行拉取,同時把每條線程的進度持久化,這樣即使中途退出、斷網、進程被殺,重新開始時也能從上次的位置接著下。

涉及的模塊不多:HTTP 請求、RandomAccessFile 隨機寫、SQLite 進度持久化、線程池。下面逐層拆開。

項目結構

一、MainActivity 的成員與 Handler

private String path = "https://192.168.1.3:8080/wanmei/yama.apk";
private String sdcardPath;

private int threadNum = 5;
ProgressDialog dialog;

private int process;      // 累計下載字節數
private int done;         // 完成百分比
private int filelength;   // 文件總長度
private int completed;    // 本次開始前已完成的下載量

// 用線程池是為了能夠優雅地中斷
ExecutorService pool;

@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
    public void handleMessage(android.os.Message msg) {
        process += msg.arg1;
        done = (int) ((1.0 * process / filelength) * 100);
        dialog.setProgress(done);

        if (done == 100) {
            // 下載完成後清理數據庫中的臨時記錄
            DBService.getInstance(getApplicationContext()).delete(path);

            // 延遲 1 秒關閉,讓用戶看清 100%
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    dialog.dismiss();
                }
            }, 1000);
        }
    }
};

用 msg.arg1 傳遞增量而非絕對值,是為了避免多線程下 Handler 消息亂序導致進度倒退。這是一個很容易被忽略的細節。

二、觸發下載

public void download(View v) {
    completed = 0;
    process = 0;
    done = 0;
    pool = Executors.newFixedThreadPool(threadNum);
    initProgressDialog();

    new Thread() {
        public void run() {
            try {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
                } else {
                    toast("沒有內存卡");
                    return;
                }
                download(path, threadNum);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.start();
}

三、HEAD 請求:先摸清目標

真正開工前,先發一次 HEAD 請求拿到文件大小與文件名,才能預先創建好本地文件、規劃每條線程的負責區間。

public void download(String path, int threadsize) throws Exception {
    URL url = new URL(path);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // 只取響應頭,不要 body:既縮短響應時間,也節省流量
    conn.setRequestMethod("HEAD");
    conn.setConnectTimeout(5 * 1000);

    filelength = conn.getContentLength();
    String filename = getFilename(path);

    // 預先創建與目標等大的本地文件
    File dir = new File(sdcardPath + "/download/");
    if (!dir.exists()) {
        dir.mkdirs();
    }
    File saveFile = new File(sdcardPath + "/download/" + filename);
    RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
    accessFile.setLength(filelength);
    accessFile.close();

    // 計算每條線程負責的數據長度(不能整除時向上取整)
    int block = filelength % threadsize == 0
            ? filelength / threadsize
            : filelength / threadsize + 1;

    // 非首次下載時,累加各線程已完成的進度
    if (!DBService.getInstance(getApplicationContext()).isHasInfors(path)) {
        for (int threadid = 0; threadid < threadNum; threadid++) {
            completed += DBService.getInstance(getApplicationContext())
                    .getInfoByIdAndUrl(threadid, path);
        }
    }

    Message msg = handler.obtainMessage();
    msg.arg1 = completed;
    handler.sendMessage(msg);

    // 提交任務到線程池
    for (int threadid = 0; threadid < threadsize; threadid++) {
        pool.execute(new DownloadThread(
                getApplicationContext(), path, saveFile, block, threadid, threadNum)
                .setOnDownloadListener(this));
    }
}

setLength(filelength) 這一步很關鍵:RandomAccessFile 允許我們直接跳到文件的任意偏移量去寫,前提是文件已經足夠大。預先「打洞」佔好空間,多個線程就能各寫各的而不互相覆蓋。

四、DownloadThread:真正的下載單元

@Override
public void run() {
    // 起始位置 = 線程id × 每塊長度 + 該線程已完成量(斷點續傳的精髓)
    completed = DBService.getInstance(context).getInfoByIdAndUrl(threadid, url);
    int startposition = threadid * block + completed;
    int endposition = (threadid + 1) * block - 1;

    try {
        RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
        accessFile.seek(startposition);

        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestProperty("Accept", "*/*");
        conn.setRequestProperty("Connection", "Keep-Alive");
        // 核心:通過 Range 頭只取自己負責的區間
        conn.setRequestProperty("RANGE", "bytes=" + startposition + "-" + endposition);

        InputStream inStream = conn.getInputStream();

        // 緩衝區大小的取捨:太小則等同限速,太大則可能 OOM
        // 這裡按剩餘可用內存在各線程間平分,動態確定
        int freeMemory = (int) Runtime.getRuntime().freeMemory();
        byte[] buffer = new byte[freeMemory / threadNum];

        int len, total = 0;
        boolean isInterrupted = false;

        while ((len = inStream.read(buffer)) != -1) {
            accessFile.write(buffer, 0, len);
            total += len;
            listener.onDownload(threadid, len, total, url);

            // 線程被中斷標記後退出循環
            if (Thread.interrupted()) {
                isInterrupted = true;
                break;
            }
        }
        inStream.close();
        accessFile.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

兩個實踐要點:

  1. HttpURLConnection 優於 HttpClient。Google 官方早已推薦前者,實測下載速度差距明顯。
  2. 緩衝區大小直接影響速度。設成 1024 字節,每次只讀 1KB,下載十幾兆的文件會慢到讓人崩潰,等同於自己給自己限速;但設得過大又會撐爆內存造成 OOM。按 freeMemory / threadNum 動態分配是一個比較平衡的折中。

五、優雅中斷

@Override
protected void onStop() {
    super.onStop();
    // 應用了退到後台就暫停下載
    pool.shutdownNow();
    dialog.dismiss();
}

shutdownNow() 並不是殘忍地殺掉線程,它做的是給所有線程打上中斷標記。於是我們在循環裡用 Thread.interrupted() 檢測,主動 break 退出,讓每條線程有機會把當前進度寫入數據庫。這才是「優雅」的含義。

六、進度回調與持久化

@Override
public void onDownload(int threadId, int process, int completed, String url) {
    DBService.getInstance(getApplicationContext())
             .updataInfos(threadId, completed, url);

    Message msg = handler.obtainMessage();
    msg.arg1 = process;
    handler.sendMessage(msg);
}

但這裡有個明顯的性能問題:不該每次讀寫都更新數據庫。SQLite 本質上是一個文件,頻繁打開關閉的開銷極大,會把下載速度拖垮。生產環境中的正確做法是:

  • 內存中維護進度,按固定時間間隔(如每 2 秒)批量落盤;
  • 或者在關鍵節點(用戶點擊暫停、網絡狀態變化、Activity 的 onStop)才觸發一次持久化。

七、DBService 關鍵方法

public class DBService {

    private DBHelper dbHelper;
    private static DBService instance;

    private DBService(Context context) {
        dbHelper = new DBHelper(context);
    }

    /** 單例,避免反覆 new 與反覆開庫 */
    public static DBService getInstance(Context context) {
        if (instance == null) {
            synchronized (DBService.class) {
                if (instance == null) {
                    instance = new DBService(context);
                    return instance;
                }
            }
        }
        return instance;
    }

    /** 判斷數據庫中是否已有該 url 的記錄 */
    public boolean isHasInfors(String urlstr) {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        Cursor cursor = database.rawQuery(
                "select count(*) from download_info where url=?",
                new String[] { urlstr });
        cursor.moveToFirst();
        int count = cursor.getInt(0);
        cursor.close();
        return count == 0;
    }

    /** 獲取指定線程已下載的進度 */
    public synchronized int getInfoByIdAndUrl(int id, String url) {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        Cursor cursor = database.rawQuery(
                "select compelete_size from download_info where thread_id=? and url=?",
                new String[] { id + "", url });
        if (cursor != null && cursor.moveToFirst()) {
            return cursor.getInt(0);
        }
        return 0;
    }

    /** 更新進度:存在則更新,不存在則插入 */
    public synchronized void updataInfos(int threadId, int compeleteSize, String urlstr) {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        String sql = "replace into download_info" +
                "(compelete_size,thread_id,url) values(?,?,?)";
        Object[] bindArgs = { compeleteSize, threadId, urlstr };
        database.execSQL(sql, bindArgs);
    }

    /** 下載完成後清理記錄 */
    public void delete(String url) {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        int count = database.delete("download_info", "url=?", new String[] { url });
        database.close();
    }
}

replace into 這一句很巧妙,它把「查詢是否存在再決定 insert 或 update」兩步合成一步,前提是 (thread_id, url) 上建了唯一索引。

可改進之處

  • 用 Content-Length 之外的信息校驗完整性,下載結束後應做一次 MD5 比對;
  • 支持 206 Partial Content 狀態碼判斷,服務器不支持 Range 時要能自動降級為單線程;
  • 加入重試機制:單條線程失敗後隔一段時間重連,而不是直接放棄整個任務;
  • 切換到 OkHttp 或 WorkManager + DownloadManager,能免費獲得連接池、攔截器和系統級的後台下載能力。

整體實現下來,代碼量並不大,但每個環節都有值得反復琢磨的取捨——這也正是下載功能雖然「爛大街」卻始終考驗工程能力的原因。

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