大文件下載必須支援斷點續傳。本文實現基於 HttpURLConnection 的多線程斷點下載器,涵蓋 Range 請求、RandomAccessFile 並發寫入、進度持久化至 SQLite/SharedPreferences、暫停/恢復/取消、指數退避重試,並提供線程安全的回調接口。
// 下載任務實體 (持久化)
@Entity(tableName = "download_task")
public class DownloadTask {
@PrimaryKey String url; // 唯一標識
String filePath; // 本地文件路徑
long totalSize; // 總大小 (-1 未知)
long downloadedSize; // 已下載總量
int threadCount; // 線程數
String etag; // 服務端 ETag,校驗文件變更
int status; // RUNNING, PAUSED, COMPLETED, FAILED
long createdAt, updatedAt;
}
// 線程分塊信息
public class Block {
int threadId;
long startOffset, endOffset; // [start, end] 閉區間
long currentOffset; // 當前寫入位置
boolean completed;
}
public class MultiThreadDownloader {
private final ExecutorService executor = Executors.newFixedThreadPool(4);
private final OkHttpClient client = new OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.build();
public void start(DownloadTask task, DownloadCallback callback) {
// 1. HEAD 請求獲取總大小、支援 Range、ETag
Request headReq = new Request.Builder().url(task.url).head().build();
try (Response headRes = client.newCall(headReq).execute()) {
if (!headRes.isSuccessful()) throw new IOException("HEAD failed: " + headRes.code());
task.totalSize = headRes.header("Content-Length", -1);
task.etag = headRes.header("ETag");
boolean acceptRanges = "bytes".equalsIgnoreCase(headRes.header("Accept-Ranges"));
if (!acceptRanges || task.totalSize <= 0) {
// 不支援範圍請求,退回單線程
singleThreadDownload(task, callback);
return;
}
}
// 2. 初始化/恢復分塊
List blocks = loadBlocks(task); // 從 DB 恢復 currentOffset
if (blocks.isEmpty()) blocks = splitBlocks(task.totalSize, task.threadCount);
// 3. 启動下載線程
CountDownLatch latch = new CountDownLatch(blocks.size());
AtomicBoolean cancelled = new AtomicBoolean(false);
for (Block block : blocks) {
executor.submit(() -> downloadBlock(task, block, cancelled, callback, latch));
}
// 4. 等待完成或取消
executor.submit(() -> {
try { latch.await(); }
catch (InterruptedException ignored) {}
if (!cancelled.get()) {
mergeBlocks(task, blocks, callback);
}
});
}
private void downloadBlock(DownloadTask task, Block block,
AtomicBoolean cancelled, DownloadCallback callback,
CountDownLatch latch) {
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(task.filePath, "rwd");
raf.seek(block.currentOffset);
Request req = new Request.Builder()
.url(task.url)
.addHeader("Range", "bytes=" + block.currentOffset + "-" + block.endOffset)
.build();
try (Response res = client.newCall(req).execute()) {
if (!res.isSuccessful() && res.code() != 206) throw new IOException("Range request failed: " + res.code());
try (InputStream is = res.body().byteStream()) {
byte[] buffer = new byte[8192];
int len;
while ((len = is.read(buffer)) != -1) {
if (cancelled.get()) return;
raf.write(buffer, 0, len);
block.currentOffset += len;
task.downloadedSize += len;
// 節流回調進度 (如每 500ms)
callback.onProgress(task);
persistBlock(block); // 異步持久化
}
block.completed = true;
}
}
} catch (IOException e) {
// 指數退避重試邏輯 (略)
block.completed = false;
} finally {
closeQuietly(raf);
latch.countDown();
}
}
// ... mergeBlocks, persistBlock, loadBlocks, singleThreadDownload 略
}
public interface DownloadCallback {
void onProgress(DownloadTask task); // 下載中,UI 更新進度條
void onCompleted(DownloadTask task); // 完成
void onFailed(DownloadTask task, Exception e); // 失敗
void onPaused(DownloadTask task); // 暫停
}
raf.setLength(totalSize) 避免寫入時擴展文件導致碎片/失敗。AtomicLong 累加 downloadedSize,避免競態。ConnectivityManager.NetworkCallback,斷網自動暫停、復網自動恢復。Foreground Service 中運行,並顯示進度通知。自研下載器適合極度定製需求;常規業務優先選用成熟庫或系統服務,專注業務邏輯創新。