Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 多線程斷點續傳下載完整實作:SQLite 記錄進度 + Range 分段請求

編輯:Android 開發實例

斷點續傳一直是 Android 開發裡讓人頭疼的環節。它考驗的不是某個 API 的用法,而是整體的邏輯組織能力:怎麼記錄已完成的進度、怎麼把檔案切成多段、怎麼在多個線程之間同步狀態。邏輯稍一凌亂,就會出現檔案損毀、進度重複下載、暫停後無法續傳等等各種問題。

本文以「下載 MP3」為例,示範一套多線程斷點續傳的完整實作,核心用到兩個技術:HTTP Range 請求與 SQLite 進度持久化。

一、原理拆解

斷點續傳的意思很直白:第一次下載到一半時使用者按了暫停或離開了 App,第二次回來時要能從上次的位置接著下載,而不是從頭再來。

要做到這件事,必須回答三個問題:

  1. 進度存在哪?答案是資料庫。這裡建立一個 download_info 表,每個下載線程一行記錄。
  2. 檔案怎麼分段?用 RandomAccessFile 先把檔案預先佔位成完整大小,再讓每個線程只負責寫入自己那一段。
  3. 伺服器怎麼只回傳一段?透過 Range: bytes=x-y 請求標頭,讓 Server 只回傳指定範圍的位元組。

二、建立資料庫:DBHelper

package cn.yj3g.DBHelper;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

    // download.db 為資料庫名稱
    public DBHelper(Context context) {
        super(context, "download.db", null, 1);
    }

    // 建立 download_info 表,用來存放各線程的下載資訊
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table download_info(_id integer PRIMARY KEY AUTOINCREMENT, "
                + "thread_id integer, start_pos integer, end_pos integer, "
                + "compelete_size integer, url char)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}

每個欄位的含義:線程編號、起始位置、結束位置、已完成位元組數,以及對應的檔案 URL。

三、主介面版面

這裡用一個 ListView 列出可下載的音樂檔名,每一列都附帶「下載」與「暫停」兩個按鈕。

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/llRoot">
    <ListView android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    </ListView>
</LinearLayout>

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dip">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/tv_resouce_name"/>
        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="下載"
            android:id="@+id/btn_start"
            android:onClick="startDownload"/>
        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="暫停"
            android:id="@+id/btn_pause"
            android:onClick="pauseDownload"/>
    </LinearLayout>
</LinearLayout>

四、兩個資料承載類別

DownloadInfo 用來記錄每個下載線程的狀態,會被寫進資料庫;LoadInfo 則是給介面用的,承載檔案總大小與已完成量,用來設定 ProgressBar 的範圍與目前值。

package cn.yj3g.entity;

/** 下載資訊實體 */
public class DownloadInfo {
    private int threadId;       // 下載器 id
    private int startPos;       // 開始點
    private int endPos;         // 結束點
    private int compeleteSize;  // 完成度
    private String url;         // 下載器網路標識

    public DownloadInfo(int threadId, int startPos, int endPos,
                        int compeleteSize, String url) {
        this.threadId = threadId;
        this.startPos = startPos;
        this.endPos = endPos;
        this.compeleteSize = compeleteSize;
        this.url = url;
    }

    public DownloadInfo() {
    }

    public String getUrl() { return url; }
    public void setUrl(String url) { this.url = url; }
    public int getThreadId() { return threadId; }
    public void setThreadId(int threadId) { this.threadId = threadId; }
    public int getStartPos() { return startPos; }
    public void setStartPos(int startPos) { this.startPos = startPos; }
    public int getEndPos() { return endPos; }
    public void setEndPos(int endPos) { this.endPos = endPos; }
    public int getCompeleteSize() { return compeleteSize; }
    public void setCompeleteSize(int compeleteSize) { this.compeleteSize = compeleteSize; }

    @Override
    public String toString() {
        return "DownloadInfo [threadId=" + threadId
                + ", startPos=" + startPos + ", endPos=" + endPos
                + ", compeleteSize=" + compeleteSize + "]";
    }
}
package cn.yj3g.entity;

/** 記載下載器詳細資訊 */
public class LoadInfo {
    public int fileSize;        // 檔案大小
    private int complete;       // 完成度
    private String urlstring;   // 下載器標識

    public LoadInfo(int fileSize, int complete, String urlstring) {
        this.fileSize = fileSize;
        this.complete = complete;
        this.urlstring = urlstring;
    }

    public LoadInfo() {
    }

    public int getFileSize() { return fileSize; }
    public void setFileSize(int fileSize) { this.fileSize = fileSize; }
    public int getComplete() { return complete; }
    public void setComplete(int complete) { this.complete = complete; }
    public String getUrlstring() { return urlstring; }
    public void setUrlstring(String urlstring) { this.urlstring = urlstring; }

    @Override
    public String toString() {
        return "LoadInfo [fileSize=" + fileSize + ", complete=" + complete
                + ", urlstring=" + urlstring + "]";
    }
}

五、核心:Downloader 下載器

這是整個範例的關鍵。它負責初始化檔案、切分線程、啟動下載、回報進度,以及提供暫停與重設的介面。請特別注意三個設計:

  • init() 先用 RandomAccessFile.setLength() 把本地檔案撐到完整大小,這樣多個線程才能各自 seek 到自己的位置寫入而不互相覆蓋。
  • 每次寫入一個 buffer 就立刻更新資料庫,這是「續傳」得以成立的基礎。
  • 暫停只是把狀態設為 PAUSE,線程在下一輪迴圈時自行退出,不做強制中斷,避免檔案寫到一半。
package cn.yj3g.service;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import cn.yj3g.Dao.Dao;
import cn.yj3g.entity.DownloadInfo;
import cn.yj3g.entity.LoadInfo;

public class Downloader {
    private String urlstr;      // 下載位址
    private String localfile;   // 保存路徑
    private int threadcount;    // 線程數
    private Handler mHandler;   // 訊息處理器
    private Dao dao;            // 資料庫工具類
    private int fileSize;       // 檔案大小
    private List<DownloadInfo> infos;

    private static final int INIT = 1;        // 初始化狀態
    private static final int DOWNLOADING = 2; // 正在下載
    private static final int PAUSE = 3;       // 暫停
    private int state = INIT;

    public Downloader(String urlstr, String localfile, int threadcount,
                      Context context, Handler mHandler) {
        this.urlstr = urlstr;
        this.localfile = localfile;
        this.threadcount = threadcount;
        this.mHandler = mHandler;
        dao = new Dao(context);
    }

    /** 判斷是否正在下載 */
    public boolean isdownloading() {
        return state == DOWNLOADING;
    }

    /**
     * 取得下載器資訊。
     * 首次下載時進行初始化,並把線程資訊寫入資料庫;
     * 非首次下載則從資料庫讀回起始位置、結束位置與已完成量。
     */
    public LoadInfo getDownloaderInfors() {
        if (isFirst(urlstr)) {
            Log.v("TAG", "isFirst");
            init();
            int range = fileSize / threadcount;
            infos = new ArrayList<DownloadInfo>();

            for (int i = 0; i < threadcount - 1; i++) {
                DownloadInfo info = new DownloadInfo(i, i * range,
                        (i + 1) * range - 1, 0, urlstr);
                infos.add(info);
            }
            // 最後一個線程要吃掉除不盡的尾段
            DownloadInfo info = new DownloadInfo(threadcount - 1,
                    (threadcount - 1) * range, fileSize - 1, 0, urlstr);
            infos.add(info);

            dao.saveInfos(infos); // 寫入資料庫
            return new LoadInfo(fileSize, 0, urlstr);
        } else {
            infos = dao.getInfos(urlstr);
            Log.v("TAG", "not isFirst size=" + infos.size());
            int size = 0;
            int compeleteSize = 0;
            for (DownloadInfo info : infos) {
                compeleteSize += info.getCompeleteSize();
                size += info.getEndPos() - info.getStartPos() + 1;
            }
            return new LoadInfo(size, compeleteSize, urlstr);
        }
    }

    /** 初始化:取得檔案大小並預先建立完整大小的本地檔 */
    private void init() {
        try {
            URL url = new URL(urlstr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            fileSize = connection.getContentLength();

            File file = new File(localfile);
            if (!file.exists()) {
                file.createNewFile();
            }
            RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
            accessFile.setLength(fileSize);
            accessFile.close();
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** 判斷是否為第一次下載 */
    private boolean isFirst(String urlstr) {
        return dao.isHasInfors(urlstr);
    }

    /** 啟動多線程下載 */
    public void download() {
        if (infos != null) {
            if (state == DOWNLOADING)
                return;
            state = DOWNLOADING;
            for (DownloadInfo info : infos) {
                new MyThread(info.getThreadId(), info.getStartPos(),
                        info.getEndPos(), info.getCompeleteSize(),
                        info.getUrl()).start();
            }
        }
    }

    public class MyThread extends Thread {
        private int threadId;
        private int startPos;
        private int endPos;
        private int compeleteSize;
        private String urlstr;

        public MyThread(int threadId, int startPos, int endPos,
                        int compeleteSize, String urlstr) {
            this.threadId = threadId;
            this.startPos = startPos;
            this.endPos = endPos;
            this.compeleteSize = compeleteSize;
            this.urlstr = urlstr;
        }

        @Override
        public void run() {
            HttpURLConnection connection = null;
            RandomAccessFile randomAccessFile = null;
            InputStream is = null;
            try {
                URL url = new URL(urlstr);
                connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(5000);
                connection.setRequestMethod("GET");
                // 關鍵:Range 標頭,格式為 bytes=x-y
                connection.setRequestProperty("Range", "bytes="
                        + (startPos + compeleteSize) + "-" + endPos);

                randomAccessFile = new RandomAccessFile(localfile, "rwd");
                randomAccessFile.seek(startPos + compeleteSize);

                is = connection.getInputStream();
                byte[] buffer = new byte[4096];
                int length = -1;
                while ((length = is.read(buffer)) != -1) {
                    randomAccessFile.write(buffer, 0, length);
                    compeleteSize += length;
                    dao.updataInfos(threadId, compeleteSize, urlstr); // 更新進度

                    // 透過 Handler 通知進度條更新
                    Message message = Message.obtain();
                    message.what = 1;
                    message.obj = urlstr;
                    message.arg1 = length;
                    mHandler.sendMessage(message);

                    if (state == PAUSE) {
                        return; // 暫停:讓線程自然結束
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                    randomAccessFile.close();
                    connection.disconnect();
                    dao.closeDb();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /** 刪除該 url 對應的下載記錄 */
    public void delete(String urlstr) {
        dao.delete(urlstr);
    }

    /** 暫停 */
    public void pause() {
        state = PAUSE;
    }

    /** 重設狀態 */
    public void reset() {
        state = INIT;
    }
}

六、資料庫操作工具類:Dao

把 SQL 邏輯集中在一個業務類裡,Downloader 只管呼叫方法,不必碰 Cursor。

package cn.yj3g.Dao;

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import cn.yj3g.DBHelper.DBHelper;
import cn.yj3g.entity.DownloadInfo;

public class Dao {
    private DBHelper dbHelper;

    public Dao(Context context) {
        dbHelper = new DBHelper(context);
    }

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

    /** 儲存下載資訊 */
    public void saveInfos(List<DownloadInfo> infos) {
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        for (DownloadInfo info : infos) {
            String sql = "insert into download_info(thread_id,start_pos, end_pos,"
                    + "compelete_size,url) values (?,?,?,?,?)";
            Object[] bindArgs = { info.getThreadId(), info.getStartPos(),
                    info.getEndPos(), info.getCompeleteSize(), info.getUrl() };
            database.execSQL(sql, bindArgs);
        }
    }

    /** 讀取下載資訊 */
    public List<DownloadInfo> getInfos(String urlstr) {
        List<DownloadInfo> list = new ArrayList<DownloadInfo>();
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        String sql = "select thread_id, start_pos, end_pos,compelete_size,url"
                + " from download_info where url=?";
        Cursor cursor = database.rawQuery(sql, new String[] { urlstr });
        while (cursor.moveToNext()) {
            DownloadInfo info = new DownloadInfo(cursor.getInt(0),
                    cursor.getInt(1), cursor.getInt(2), cursor.getInt(3),
                    cursor.getString(4));
            list.add(info);
        }
        cursor.close();
        return list;
    }

    /** 更新下載進度 */
    public void updataInfos(int threadId, int compeleteSize, String urlstr) {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        String sql = "update download_info set compelete_size=? "
                + "where thread_id=? and url=?";
        Object[] bindArgs = { compeleteSize, threadId, urlstr };
        database.execSQL(sql, bindArgs);
    }

    /** 關閉資料庫 */
    public void closeDb() {
        dbHelper.close();
    }

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

七、按鈕事件與進度更新:MainActivity

這裡有兩個容易忽略的細節:一是用 Map 把「下載器」與「進度條」按 URL 配對管理,支援多檔同時下載;二是進度條不能直接在子線程更新,必須透過 Handler 派送訊息。

package cn.yj3g.AndroidDownload;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.ListActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import cn.yj3g.entity.LoadInfo;
import cn.yj3g.service.Downloader;

public class MainActivity extends ListActivity {
    // 資源伺服器位址,實務上可改為遠端網址
    private static final String URL = "https://192.168.1.105:8080/struts2_net/";
    // 存放下載檔案的路徑:SD 卡根目錄
    private static final String SD_PATH = "/mnt/sdcard/";

    private Map<String, Downloader> downloaders = new HashMap<String, Downloader>();
    private Map<String, ProgressBar> ProgressBars = new HashMap<String, ProgressBar>();

    /** 以訊息機制即時更新進度條 */
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                String url = (String) msg.obj;
                int length = msg.arg1;
                ProgressBar bar = ProgressBars.get(url);
                if (bar != null) {
                    bar.incrementProgressBy(length);
                    if (bar.getProgress() == bar.getMax()) {
                        Toast.makeText(MainActivity.this, "下載完成!", 0).show();
                        // 清除進度條並清空相關狀態
                        LinearLayout layout = (LinearLayout) bar.getParent();
                        layout.removeView(bar);
                        ProgressBars.remove(url);
                        downloaders.get(url).delete(url);
                        downloaders.get(url).reset();
                        downloaders.remove(url);
                    }
                }
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        showListView();
    }

    /** 建立清單資料 */
    private void showListView() {
        List<Map<String, String>> data = new ArrayList<Map<String, String>>();
        Map<String, String> map = new HashMap<String, String>();
        map.put("name", "mm.mp3");
        data.add(map);
        map = new HashMap<String, String>();
        map.put("name", "pp.mp3");
        data.add(map);
        map = new HashMap<String, String>();
        map.put("name", "tt.mp3");
        data.add(map);
        map = new HashMap<String, String>();
        map.put("name", "You.mp3");
        data.add(map);

        SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.list_item,
                new String[] { "name" }, new int[] { R.id.tv_resouce_name });
        setListAdapter(adapter);
    }

    /** 開始下載 */
    public void startDownload(View v) {
        LinearLayout layout = (LinearLayout) v.getParent();
        String musicName = ((TextView) layout.findViewById(
                R.id.tv_resouce_name)).getText().toString();
        String urlstr = URL + musicName;
        String localfile = SD_PATH + musicName;

        int threadcount = 4; // 示範固定為 4 條線程

        Downloader downloader = downloaders.get(urlstr);
        if (downloader == null) {
            downloader = new Downloader(urlstr, localfile, threadcount, this, mHandler);
            downloaders.put(urlstr, downloader);
        }
        if (downloader.isdownloading())
            return;

        LoadInfo loadInfo = downloader.getDownloaderInfors();
        showProgress(loadInfo, urlstr, v);
        downloader.download();
    }

    /** 動態建立並掛上進度條 */
    private void showProgress(LoadInfo loadInfo, String url, View v) {
        ProgressBar bar = ProgressBars.get(url);
        if (bar == null) {
            bar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
            bar.setMax(loadInfo.getFileSize());
            bar.setProgress(loadInfo.getComplete());
            ProgressBars.put(url, bar);
            LinearLayout.LayoutParams params =
                    new LayoutParams(LayoutParams.FILL_PARENT, 5);
            ((LinearLayout) ((LinearLayout) v.getParent()).getParent())
                    .addView(bar, params);
        }
    }

    /** 暫停下載 */
    public void pauseDownload(View v) {
        LinearLayout layout = (LinearLayout) v.getParent();
        String musicName = ((TextView) layout.findViewById(
                R.id.tv_resouce_name)).getText().toString();
        String urlstr = URL + musicName;
        downloaders.get(urlstr).pause();
    }
}

八、別忘了權限

最後在 AndroidManifest.xml 註冊網路與寫入外部儲存空間的權限,否則會在執行期直接抛出例外。

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

九、實作後的幾點提醒

這套寫法在教學上很清晰,但若要上 production,還有幾件事值得補強:進度寫庫的頻率過高會拖累效能,可以改成每寫入若干 KB 或每隔數百毫秒才落檔一次;同一個檔案重複點擊下載時,要注意 Map 的執行緒安全;另外若 Server 不支援 Range 請求,就必須退回單線程下載。這些都是把「能跑」變成「跑得穩」的必經功課。

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