編輯:關於 Android 程式設計
要談多執行緒下載,得先理解單執行緒下載為什麼慢。

單執行緒就是一個任務从头做到尾,速度自然受限。

而三個執行緒分頭下載同一個檔案的不同片段,總比一個執行緒獨力完成快得多。

關鍵在於:每個執行緒負責哪一段位元組範圍,以及各自把資料寫到檔案的哪個位置。想清楚這兩件事,就可以開始寫程式了。
要分配下載量,首先得知道檔案有多大。我在本機架了一個服務,檔案名為 Wireshark.exe:

public void downloade(View v) {
Thread thread = new Thread() {
// 伺服器位址
String path = "https://192.168.1.123:8080/Wireshark.exe";
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
if (conn.getResponseCode() == 200) {
// 取得檔案總大小
int length = conn.getContentLength();
// 每個執行緒要下載的大小
int size = length / threadCount;
for (int i = 0; i < threadCount; i++) {
int startIndex = i * size;
int endIndex = (i + 1) * size - 1;
// 最後一個執行緒要吃到檔案結尾
if (i == threadCount - 1) {
endIndex = length - 1;
}
System.out.println("線程" + i + "的下載區間為:" + startIndex + "---" + endIndex);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
}
輸出結果:

可以看到區間計算正確,總大小為 29849552 位元組。這裡有個細節必須注意:最後一個執行緒的 endIndex 要特別指定為 length - 1,因為檔案大小未必能被執行緒數整除,餘數會落在最后一段。
下載開始前,先在儲存裝置上配置一個與目標檔案等大的暫存檔,這樣可以避免下載途中因空間不足而失敗。
System.out.println("線程" + i + "的下載區間為:" + startIndex + "---" + endIndex);
// 啟動 threadCount 個執行緒
new downloadThread(startIndex, endIndex, i).start();
class downloadThread extends Thread {
int startIndex; // 起始位置
int endIndex; // 結束位置
int threadId; // 執行緒編號
public downloadThread(int startIndex, int endIndex, int threadId) {
super();
this.startIndex = startIndex;
this.endIndex = endIndex;
this.threadId = threadId;
}
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
// 透過 Range 標頭只請求本執行緒負責的區間
conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
// 部分內容請求成功會回傳 206
if (conn.getResponseCode() == 206) {
InputStream is = conn.getInputStream();
byte[] b = new byte[1024];
int len = 0;
int total = 0;
File file = new File(Environment.getExternalStorageDirectory(), filename);
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
// 把寫入位置移到本執行緒的起點
raf.seek(startIndex);
while ((len = is.read(b)) != -1) {
raf.write(b, 0, len);
total += len;
System.out.println("線程" + threadId + "下載了" + total);
}
System.out.println("線程" + threadId + "---------------下載完畢-------------------");
raf.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
這裡有兩個關鍵 API:Range 請求標頭讓伺服器只回傳指定區間(回應碼為 206 而非 200),RandomAccessFile.seek() 則讓我們能把資料寫到檔案的任意偏移位置。兩者搭配,多個執行緒才能各自寫入同一個檔案而不互相覆蓋。
下載過程要讓使用者看得到進度。先把 ProgressBar 的最大值設為檔案總大小:
int length = conn.getContentLength(); pBar.setMax(length); int size = length / threadCount;
每寫入一段就累加目前進度,注意這裡要統計的是所有執行緒的總和:
raf.write(b, 0, len);
total += len;
System.out.println("線程" + threadId + "下載了" + total);
currProgress += len;
pBar.setProgress(currProgress);
文字標籤顯示百分比時,用 Handler 更新 UI:
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
// 轉成 long 運算,避免 int 溢位
tView.setText((long) pBar.getProgress() * 100 / pBar.getMax() + "%");
}
};
效果如下:

多執行緒下載完成後,下一個問題是:如果中途斷網或被終止,重新開始時能否接續?做法是把每個執行緒已下載的位元組數寫入一個進度檔,重來時讀回並調整起始位置。
啟動時先讀取上次的進度:
File bakFile = new File(Environment.getExternalStorageDirectory(), threadId + ".txt");
try {
if (bakFile.exists()) {
FileInputStream fis = new FileInputStream(bakFile);
BufferedReader bReader = new BufferedReader(new InputStreamReader(fis));
// 讀出上次已下載的量,加到原本的起始位置上
int lastProgress = Integer.parseInt(bReader.readLine());
startIndex += lastProgress;
// 同步更新進度條與文字
currProgress += lastProgress;
pBar.setProgress(currProgress);
handler.sendEmptyMessage(1);
fis.close();
}
} catch (Exception e) {
e.printStackTrace();
}
下載迴圈中,每寫入一段就把累計進度存回設定檔:
while ((len = is.read(b)) != -1) {
raf.write(b, 0, len);
total += len;
System.out.println("線程" + threadId + "下載了" + total);
currProgress += len;
pBar.setProgress(currProgress);
handler.sendEmptyMessage(1);
// 將目前進度寫入設定檔,供下次續傳使用
RandomAccessFile bakRaFile = new RandomAccessFile(bakFile, "rwd");
bakRaFile.write((total + "").getBytes());
bakRaFile.close();
}
如此一來,斷點續傳就能正常工作了。

下載完成的檔案可以正常執行(我把範例檔案換成了體積較小的 feather 檔案,Wireshark 實在太大)。
Range 支援是前提。伺服器必須回應 206 並提供 Accept-Ranges 標頭,否則整個方案不成立。實作前最好先確認後端支援情況。
進度檔的寫入頻率。上面範例每寫 1KB 就存檔一次,I/O 太頻繁。實務上可以改成每完成固定百分比或每隔數秒才落盤,兼顧效能與安全性。
執行緒數不是越多越好。過多執行緒會導致頻寬競爭與連線開銷上升,一般 3 到 5 條是常見的甜蜜點。
權限與相容性。寫入外部儲存需要相關權限,Android 6.0 以上還要處理動態授權;Android 10 以上則建議改用儲存空間存取架構或 app 專屬目錄。
Android 官方文件導讀:Content Providers 完整解析
ContentProvider 是 Android 四大元件之一,用於管理應用程式對結構化資料的存取。它把資料封裝起來(encapsulate the data),同時提
Android Activity 回傳資料:startActivityForResult 實作解析
回傳資料的需求 有些情境下,我們不只是要開啟另一個 Activity,還希望它結束後把結果帶回來。例如選擇聯絡人、選擇號碼或挑選圖片。 startActivityFor
Android 动画进阶(三):属性动画 PropertyAnimation 完全指南
属性动画的问世,正是为了弥补前两种动画模式的不足(它是 Android 3.0 之后才有的)。其特点在于:真实地改动 view 的属性,并且能支持自定义属性动画,基本上能
我們為什麼要在 Android 中使用 RxJava
近來 RxJava 風生水起,不學一下都不好意思了。本人也是初學 RxJava,起初還覺得代碼好像更複雜、更難懂了,直到讀到一篇外文深有共鳴,便簡單翻譯過來分享給大家。本