編輯:關於 Android 程式設計
大檔案下載若只用單線程,速度慢且一旦中斷就得從頭來過。多執行緒斷點續傳的原理並不複雜,本文從原理一路寫到 Android 版本的可執行範例。
第一步:先在本地開一個與伺服器同大小檔案。
要隨機寫入,必須先知道檔案總長度。透過 HTTP 回應標頭中的 Content-Length 取得大小,再用 RandomAccessFile 建立檔案並呼叫 setLength() 預先配置空間。
第二步:切塊並開多個執行緒。
把總長度除以執行緒數(範例用 3),算出每條執行緒負責的起訖位置,透過請求標頭 Range: bytes=start-end 讓伺服器只回傳該區段。各執行緒用 seek() 把檔案指針移到自己的起點後寫入。
第三步:記錄進度以支援續傳。
每條執行緒配一個 id.txt 檔,持續寫入自己已下載到的位置。下次啟動時讀回這個數字,若它大於原定起點,就從該位置續傳。
public class TestMutileDownload {
public static final String path = "https://192.168.1.247:8080/youdao.exe";
public static int threadcount;
public static void main(String[] args) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setConnectTimeout(5000);
// 取得伺服器檔案大小
int len = conn.getContentLength();
System.out.println("檔案大小為" + len);
// 在本地建立同大小的檔案
File file = new File("youdao.exe");
RandomAccessFile randomfile = new RandomAccessFile(file, "rwd");
randomfile.setLength(len);
// 假設只開啟 3 個子執行緒
int blocksize = len / 3;
for (int i = 1; i <= 3; i++) {
threadcount = 0;
int startsize = (i - 1) * blocksize;
int endsize = i * blocksize - 1;
if (i == 3) {
endsize = len;
}
new Thread(new DownLoadTask(i, startsize, endsize)).start();
}
}
}
執行緒類別:
class DownLoadTask implements Runnable {
private int id;
private int startsize;
private int endsize;
public DownLoadTask(int id, int startsize, int endsize) {
this.id = id;
this.startsize = startsize;
this.endsize = endsize;
}
@Override
public void run() {
try {
File idfile = new File(id + ".txt");
// 判斷是否有已下載的位置記錄
if (idfile.exists()) {
FileInputStream fis = new FileInputStream(idfile);
byte[] result = StreamTools.getBytes(fis);
String numberstr = new String(result);
if (numberstr != null && !"".equals(numberstr)) {
int startposition = Integer.parseInt(numberstr);
if (startposition > startsize) {
startsize = startposition; // 重新指定下載起點
}
}
}
URL url = new URL(TestMutileDownload.path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setConnectTimeout(5000);
// 指定本執行緒的下载區段
if (startsize > endsize) {
startsize = endsize - 1;
}
conn.setRequestProperty("Range", "bytes=" + startsize + "-" + endsize);
InputStream is = conn.getInputStream();
RandomAccessFile randomfile =
new RandomAccessFile(new File("youdao.exe"), "rwd");
randomfile.seek(startsize);
byte[] buffer = new byte[1024];
int len = 0;
int total = 0;
while ((len = is.read(buffer)) != -1) {
randomfile.write(buffer, 0, len);
total += len;
// 記錄當前執行緒下載到的位置
FileOutputStream idfos = new FileOutputStream(idfile);
idfos.write((startsize + total + "").getBytes());
idfos.flush();
idfos.close();
}
randomfile.close();
is.close();
synchronized (TestMutileDownload.class) {
TestMutileDownload.threadcount++;
if (TestMutileDownload.threadcount >= 3) {
System.out.println("所有執行緒都執行完畢了");
for (int i = 1; i <= 3; i++) {
File deletefile = new File(i + ".txt");
deletefile.delete();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
搬到 Android 上有三處必須調整:
一是存檔位置改到 Environment.getExternalStorageDirectory(),並在清單檔補上 WRITE_EXTERNAL_STORAGE 權限(Android 6.0 起還要動態申請)。
二是進度條更新必須回到主執行緒。子執行緒只能透過 Handler 發送 Message,由主執行緒的 handleMessage() 更新 ProgressBar,直接從子執行緒操作 View 會導致 CalledFromWrongThreadException。
三是暂停機制。用一個 flag 旗標控制,按下暫停時設為 false,各執行緒在寫入循環中檢查到旗標變 false 就 return 退出;此時 id.txt 已記錄了當前位置,下次點擊下載即可接續。
另外要提醒,範例中每寫入 1KB 就開關一次 id.txt,IO 頻率過高會明顯拖慢速度。實務上宜改為累計到一定門檻(例如 64KB)或每隔數秒才落檔一次。
Android 自訂 Toast 提示訊息的實作方法
為什麼要自訂 Android 系統預設的 Toast 十分簡潔,使用也非常簡單。但有時候預設樣式與整體介面風格格格不入,這時就需要自訂 Toast,讓它與你的應用更為融合
Android 非同步上傳圖片到 PHP 伺服器
原理 Android 客戶端模擬一個 HTTP POST 請求打到伺服器,伺服器接收後處理並回傳響應內容給客戶端。 背景 網路上大多是上傳到 Java 伺服器的教學,找
Android 學習啟程:從 Java、Dalvik 到 Linux Kernel 的入門地圖
行動平台觀察 近年行動平台快速成長,iOS 與 Android 是最受關注的兩大系統。Android 的開放性與生態系,使其成為許多開發者入門與創作的舞台。 學習前置 A
搶紅包插件實現原理淺析
搶紅包,先看效果圖~ 實現自動搶紅包,要解決兩個問題: 一、如何實時監聽發紅包的事件 二、如何在紅包到來時自動進入頁面並自動點擊紅包 一、如何獲取紅包到來的事件