編輯:關於 Android 程式設計
單執行緒下載一個幾十 MB 的檔案,使用者盯著 0% 看實在煎熬。多執行緒下載的價值有兩個:把頻寬吃得更滿,以及斷線之後能從上次的位置接著跑。做法是先用 HTTP 的 Range 標頭把檔案切成好幾段,每個執行緒各寫自己那一段。
整個機制靠三個零件支撐:HttpURLConnection 搭配 Range: bytes=start-end 要求伺服器只回傳某個區間;RandomAccessFile 讓多個執行緒可以對「同一個檔案」的不同位移各自寫入而不互相覆蓋;以及把每個執行緒已下載的長度寫到一個小檔案裡,重來時讀回來當作起點,這就是斷點續傳。
public void downLoad(View v) {
MainActivity.flag = true;
MainActivity.pb_count = 0;
path = et_url.getText().toString();
String threadNum_et = et_num.getText().toString();
if (TextUtils.isEmpty(path) || TextUtils.isEmpty(threadNum_et)) {
Toast.makeText(this, "不能為空", Toast.LENGTH_LONG).show();
return;
}
threadNum = Integer.valueOf(threadNum_et);
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)");
if (conn.getResponseCode() == 200) {
size = conn.getContentLength();
pb_thread.setMax(size);
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File sdFile = Environment.getExternalStorageDirectory();
File file = new File(sdFile, "youdao.exe");
RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
accessFile.setLength(size); // 先預留完整大小
blockSize = size / threadNum; // 每段的大小
for (int i = 1; i <= threadNum; i++) {
int startSize = (i - 1) * blockSize;
int endSize = i * blockSize;
if (i == threadNum && size > endSize) {
endSize = size; // 最後一段吃掉餘數
}
RandomAccessFile threadAccessFile =
new RandomAccessFile(file, "rwd");
new Thread(new DownLoadThread(i, threadAccessFile,
startSize, endSize, path)).start();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
// 暫停:把旗標設為 false,各執行緒下一輪迴圈就會自行退出
public void downPause(View v) {
Toast.makeText(this, "暫停", Toast.LENGTH_LONG).show();
this.flag = false;
}
public class DownLoadThread implements Runnable {
public RandomAccessFile accessFile;
public int startSize;
public int endSize;
public String path;
public int threadId;
public DownLoadThread(int threadId, RandomAccessFile accessFile,
int startSize, int endSize, String path) {
this.threadId = threadId;
this.accessFile = accessFile;
this.startSize = startSize;
this.endSize = endSize;
this.path = path;
}
@Override
public void run() {
try {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File sdFile = Environment.getExternalStorageDirectory();
File threadFile = new File(sdFile, threadId + ".txt");
// 讀回上次的進度,實現斷點續傳
if (threadFile.exists()) {
byte[] data = StreamTools.isToData(new FileInputStream(threadFile));
String threadLen = new String(data);
if (threadLen != null && !"".equals(threadLen)) {
startSize = Integer.valueOf(threadLen);
if (startSize > endSize) {
startSize = endSize - 1; // 避開 416 錯誤
}
}
}
HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setRequestProperty("Range", "bytes=" + startSize + "-" + endSize);
accessFile.seek(startSize); // 關鍵:定位到該段起點
InputStream is = conn.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
int threadTotal = 0;
while ((len = is.read(buffer)) != -1) {
accessFile.write(buffer, 0, len);
threadTotal += len;
setProgressBar(len);
// 把已下載長度寫進小檔案,供下次續傳
FileOutputStream fos = new FileOutputStream(threadFile);
fos.write((threadTotal + "").getBytes());
fos.flush();
fos.close();
MainActivity.handler.sendEmptyMessage(MainActivity.TEXTVALUE);
if (!MainActivity.flag) {
return; // 收到暫停指令
}
}
accessFile.close();
is.close();
synchronized (MainActivity.class) {
MainActivity.threadCount++;
if (MainActivity.threadCount >= MainActivity.threadNum) {
for (int i = 1; i <= MainActivity.threadNum; i++) {
File deleteFile = new File(sdFile, i + ".txt");
if (deleteFile.exists()) {
deleteFile.delete(); // 全部完成後清掉進度檔
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void setProgressBar(int len) {
MainActivity.pb_count += len;
MainActivity.pb_thread.setProgress(MainActivity.pb_count);
}
}
public class StreamTools {
public static byte[] isToData(InputStream is) throws IOException {
ByteArrayOutputStream bops = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
bops.write(buffer, 0, len);
}
byte[] data = bops.toByteArray();
bops.flush();
bops.close();
is.close();
return data;
}
}
為什麼要判斷 startSize > endSize 並回退一格?因為檔案已經下載完畢時,續傳的起點會等於甚至超過終點,伺服器收到不合法的 Range 會回 416 Requested Range Not Satisfiable,下載就卡死了。
進度條為什麼要用 Handler?因為 Android 只允許在建立 View 的那條執行緒上更新 UI。這裡的做法是各下載執行緒把長度累加到共用的計數器,再送空訊息給 Handler,由 Handler 在 UI 執行緒上把百分比寫進 TextView。順帶一提,範例中 pb_count += len 與 setProgress 之間的同步是靠 synchronized 保住計數正確,但 setProgress 本身仍應回到 UI 執行緒呼叫才嚴謹。
最後,這套程式有幾個時代痕跡值得注意:外部儲存權限在 Android 6.0 之後需要執行期動態申請,Android 10 更導入 Scoped Storage,直接寫 Environment.getExternalStorageDirectory() 已不再是建議做法;清除暫停旗標也只是讓執行緒自己退出,並未真正釋放連線。若要重用它,把「檔案落地」換成 app 私有目錄或 MediaStore,下載核心則可考慮 WorkManager 搭配 OkHttp。
Android 模擬定位實戰:從權限設定到 GPS 位置注入
這篇筆記整理了 Android 模擬位置的使用方法,支援到 Android 6.0,供大家參考。 一、開啟系統的模擬位置 Android 6.0 以下:進入【開發者選項
驗證碼倒計時按鈕實現:Android賬號注冊常見交互
為防止惡意刷短信或郵件,注冊頁面的「獲取驗證碼」按鈕通常都要做倒計時處理:點擊後按鈕變灰並開始倒數,倒數結束才能再次點擊。本文分享一個可複用的封裝思路。 效果預覽 Re
Android 依賴注入實戰:Dagger 2 入門教學(一)
Dagger 2 是由 Google 的技術團隊主導開發的依賴注入框架,Square 的成員與許多貢獻者也都投入其中。相比 Dagger 1.x,它在編譯期就能生成程式碼
Android 基礎再學習:Activity 的狀態保存機制
學習 Activity 生命週期時我們知道,當 Activity 進入 paused 或 stopped 狀態後,其狀態仍被保存著——因為該 Activity 物件仍在記