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

Android 多執行緒斷點續傳下載與檔案上傳實作

編輯:關於 Android 程式設計

檔案傳輸是每個 Android 開發者都會碰到的題目。本文示範兩個主題:一是用多執行緒分段下載搭配 SharedPreferences 記錄斷點,做到中途退出還能續傳;二是用multipart 表單上傳把檔案送到伺服器端。

一、下載功能的整體思路

整個流程可以拆成四個階段:

1. 建立介面:一個主佈局放輸入框、按鈕與容器,另一個子佈局只放一個 ProgressBar,用來為每個執行緒產生一條進度條。

2. 綁定點擊事件:讀取使用者輸入的執行緒數 → 清空容器 → 動態加入對應數量的 ProgressBar → 開子執行緒呼叫 download()(主執行緒不能做長時間的網路操作)。

3. download() 分配任務:請求網路取得檔案總大小 → 在本地建立同尺寸的佔位檔案 → 依執行緒數把範圍切段 → 每段啟動一個下載執行緒。

4. 單執行緒下載類別:從 map 取得自己對應的 ProgressBar → 讀取 SharedPreferences 裡的斷點 → 帶上 Range 標頭做分段請求 → 邊讀邊寫入佔位檔 → 每寫一段就更新斷點與進度。

二、佈局建立

主佈局包含輸入框、下載按鈕與進度條容器:

<linearlayout android:layout_height="match_parent" android:layout_width="match_parent"
    android:orientation="vertical"
    android:paddingbottom="@dimen/activity_vertical_margin"
    android:paddingleft="@dimen/activity_horizontal_margin"
    android:paddingright="@dimen/activity_horizontal_margin"
    android:paddingtop="@dimen/activity_vertical_margin"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <edittext android:id="@+id/et_threadCount"
        android:layout_height="wrap_content" android:layout_width="fill_parent" />

    <button android:id="@+id/bt_download"
        android:layout_height="wrap_content" android:layout_width="fill_parent"
        android:text="立即下載" />

    <linearlayout android:id="@+id/ll_progress_layout"
        android:layout_height="wrap_content" android:layout_width="fill_parent"
        android:orientation="vertical" />
</linearlayout>

子佈局只有一個 ProgressBar,會被 inflate 多次:

<progressbar android:layout_height="match_parent" android:layout_width="match_parent"
    xmlns:android="https://schemas.android.com/apk/res/android" />

記得在清單檔加上網路權限與寫入外部儲存空間的權限,6.0 以上後者還要執行期申請。

三、點擊事件

先定義會用到的全域變數:

public class MainActivity extends Activity implements OnClickListener {

    private EditText et_threadCount;
    private Context mContext;
    private LinearLayout ll_progress_layout;
    private int threadCount = 0;        // 執行緒數量
    private int blockSize = 0;          // 每個執行緒的理論下載大小
    private String path = "https://115.25.200.74:8080/itheima74/feiq.exe";
    private Map<Integer, ProgressBar> map = new HashMap<Integer, ProgressBar>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        findViewById(R.id.bt_download).setOnClickListener(this);
        ll_progress_layout = findViewById(R.id.ll_progress_layout);
        et_threadCount = findViewById(R.id.et_threadCount);
    }

    @Override
    public void onClick(View v) {
        threadCount = Integer.parseInt(et_threadCount.getText().toString().trim());
        ll_progress_layout.removeAllViews();            // 清掉舊的進度條
        for (int i = 0; i < threadCount; i++) {
            ProgressBar progressbar = (ProgressBar) View.inflate(
                    mContext, R.layout.child_progressbar_layout, null);
            map.put(i, progressbar);                    // 存起來供執行緒取用
            ll_progress_layout.addView(progressbar);
        }
        new Thread(new Runnable() {
            @Override
            public void run() { download(); }
        }).start();
    }
}

四、下載位置的計算

先請求一次取得檔案大小,並在本地建立佔位檔:

// 1. 請求 URL 取得服務端資源大小
URL url = new URL(path);
HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
openConnection.setRequestMethod("GET");
openConnection.setConnectTimeout(10 * 1000);

int code = openConnection.getResponseCode();
if (code == 200) {
    int filelength = openConnection.getContentLength();
    // 2. 建立與服務端同大小的佔位檔
    RandomAccessFile randomAccessFile =
            new RandomAccessFile(new File(getFileName(path)), "rw");
    randomAccessFile.setLength(filelength);

    // 3. 把範圍切給每個執行緒
    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;      // 最後一段要吃掉餘數
        }
        // 4. 啟動下載執行緒
        new DownloadThread(threadId, startIndex, endIndex).start();
    }
}

切段時務必讓最後一個執行緒的結束位置等於 filelength - 1,因為整除會留下餘數,否則檔案尾端會有一小塊永遠下載不到。

五、下載執行緒

參數初始化,並計算該執行緒的進度條最大值:

private int threadId;
private int startIndex;
private int endIndex;
private int lastPostion;
private int currentThreadTotalProgress;

public DownloadThread(int threadId, int startIndex, int endIndex) {
    this.threadId = threadId;
    this.startIndex = startIndex;
    this.endIndex = endIndex;
    this.currentThreadTotalProgress = endIndex - startIndex + 1;
}

用 SharedPreferences 保存與讀取每個執行緒的斷點:

public class SharedUtils {
    public static int getLastPosition(Context context, int threadId) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        return sp.getInt("lastPostion" + threadId, -1);
    }
    public static void setLastPosition(Context context, int threadId, int position) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        sp.edit().putInt("lastPostion" + threadId, position).commit();
    }
}

接著設定分段下載的 Range 標頭,這是斷點續傳的關鍵——伺服器會據此只回傳指定區間的位元組:

try {
    URL url = new URL(path);
    HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
    openConnection.setRequestMethod("GET");
    openConnection.setConnectTimeout(10 * 1000);

    if (SharedUtils.getLastPosition(mContext, threadId) != -1) {
        lastPostion = SharedUtils.getLastPosition(mContext, threadId);
        if (lastPostion == endIndex + 1) {
            // 該執行緒上次已下載完成,直接標記進度
            progressBar.setProgress(currentThreadTotalProgress);
        }
    } else {
        lastPostion = startIndex;
    }
    // Range: bytes=start-end,做分段資料請求
    openConnection.setRequestProperty("Range", "bytes:" + lastPostion + "-" + endIndex);

請求成功後(206 Partial Content 代表部分資源請求成功),一邊讀一邊寫入佔位檔的對應位置:

    if (openConnection.getResponseCode() == 206) {
        InputStream inputStream = openConnection.getInputStream();
        RandomAccessFile randomAccessFile =
                new RandomAccessFile(new File(getFileName(path)), "rw");
        randomAccessFile.seek(lastPostion);         // 從斷點位置開始寫

        byte[] buffer = new byte[1024 * 100];
        int length = -1;
        int total = 0;
        while ((length = inputStream.read(buffer)) != -1) {
            randomAccessFile.write(buffer, 0, length);
            total += length;
            int currentThreadPostion = lastPostion + total;
            SharedUtils.setLastPosition(mContext, threadId, currentThreadPostion);
            int currentprogress = currentThreadPostion - startIndex;
            progressBar.setMax(currentThreadTotalProgress);
            progressBar.setProgress(currentprogress);   // 這裡有問題,見下方說明
        }
        inputStream.close();
        randomAccessFile.close();
    }
} catch (Exception e) {
    e.printStackTrace();
}

兩個路徑輔助方法:

public String getFileName(String url) {
    return Environment.getExternalStorageDirectory() + "/"
            + url.substring(url.lastIndexOf("/") + 1);
}
public String getFilePath() {
    return Environment.getExternalStorageDirectory() + "/";
}

這裡要特別指出一個 bug:上面的 progressBar.setProgress() 是在子執行緒呼叫的,而 Android 只允許建立 View 的那條執行緒去改它,否則會丟出 CalledFromWrongThreadException。正確做法是用 runOnUiThread 或 Handler 把更新丟回主執行緒,並搭配節流(例如每 100ms 才更新一次),否則大量跨執行緒呼叫反而會拖慢下載。

六、原稿提到的兩個問題,其實都有答案

「下載在 2.3 能跑,4.1 卻不行」——這是 Android 4.0 導入 StrictMode 的直接後果。從 API 9 起,主執行緒發生網路或磁碟 I/O 就會拋出 NetworkOnMainThreadException 或 StrictModeDiskRead。2.3 沒有這個檢查所以能跑。解法是把所有網路與檔案操作都放進子執行緒,程式碼如上。

「先開 3 個執行緒,中斷後改填 5 個,只有最後兩個在跑」——因為切換執行緒數時,旧的 SharedPreferences 斷點並沒有被清掉。新舊 threadId 的斷點混在一起,新配置下前幾段的起點與斷點位置對不上,Range 請求就失敗了。實務上的做法是:把斷點紀錄連同檔案總大小、執行緒數一起存進一個 json 或 sp,啟動時先比對是否吻合,不吻合就整批作廢重來。


檔案上傳

下載之外,上傳也是必備功能。整體分兩邊:客戶端用開源 HTTP 套件把檔案包成 multipart 表單 POST 出去;伺服器端用 Commons FileUpload 解析。

一、思路

客戶端:佈局放一個 EditText 一個 Button → 取得輸入的檔案路徑 → 呼叫開源 Utils 上傳。

伺服器端:先判斷請求是表單資料還是帶檔案的資料 → 若是帶檔案,在本地建立存放目錄 → 逐項判斷型別,表單欄位就印出來,檔案欄位就寫入磁碟。

二、佈局

<relativelayout android:layout_height="match_parent" android:layout_width="match_parent"
    android:paddingbottom="@dimen/activity_vertical_margin"
    android:paddingleft="@dimen/activity_horizontal_margin"
    android:paddingright="@dimen/activity_horizontal_margin"
    android:paddingtop="@dimen/activity_vertical_margin"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <edittext android:id="@+id/et_filepath"
        android:layout_height="wrap_content" android:layout_width="fill_parent" />

    <button android:id="@+id/bt_upload"
        android:layout_below="@id/et_filepath"
        android:layout_height="wrap_content" android:layout_width="fill_parent"
        android:onclick="fileupload" android:text="上傳" />
</relativelayout>

三、客戶端

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void fileupload(View v) {
        try {
            EditText et_filepath = findViewById(R.id.et_filepath);
            String filepath = et_filepath.getText().toString().trim();

            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            RequestParams params = new RequestParams();
            params.put("filename", new File(filepath));
            asyncHttpClient.post(
                    "https://115.25.200.74:8080/itheima74/servlet/UploaderServlet",
                    params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    if (statusCode == 200) {
                        Toast.makeText(MainActivity.this, "上傳成功", 0).show();
                    }
                }
                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                    Toast.makeText(MainActivity.this, "上傳失敗", 0).show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

四、伺服器端

先判斷資料型別,再逐項處理:是表單就印出,是檔案就寫入以時間戳命名的檔案:

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // 先判斷是表單資料還是帶檔案的資料
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        String realpath = request.getSession().getServletContext().getRealPath("/files");
        File dir = new File(realpath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        try {
            List<fileitem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // 表單欄位
                    String name = item.getFieldName();
                    String value = item.getString("UTF-8");
                    System.out.println(name + "=" + value);
                } else {
                    // 檔案欄位:以時間戳 + 原始副檔名命名後寫入
                    String fileName = System.currentTimeMillis()
                            + item.getName().substring(item.getName().lastIndexOf("."));
                    item.write(new File(dir, fileName));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

實務上有幾點要補強:伺服器端只實作了 doGet,上傳應該走 doPost;檔名要過濾 ../ 這類路徑穿越字元;檔案大小要設上限,避免 DiskFileItemFactory 把整個上傳暫存進記憶體或磁碟造成風險;上傳也需要進度條,AsyncHttpClient 可搭配 RequestParams.setForceMultipartEntityContentType 與自訂的進度回呼來達成。


總結

多執行緒下載的核心其實只有三件事:RandomAccessFile 隨機寫入讓多條執行緒能各寫各的區塊、HTTP Range 標頭讓伺服器只回傳需要的區段、持久化斷點讓進度能跨 process 存活。這三個觀念弄懂了,換成 OkHttp、改用 WorkManager 排程、或加上檢查檔案 MD5 驗證完整性,都只是在此骨架上加裝。

現代的建議做法:下載用 WorkManager 或 DownloadManager 交給系統排程(能處理網路變化、低電量、重試與通知列進度),HTTP 層用 OkHttp 取代已停止維護的 HttpClient,檔案路徑改用 getExternalFilesDir() 或 MediaStore 以避開 Android 10 之後的分區儲存限制。

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