7.3.3 Android 文件下载(2)
系统拆解 Android 多线程断点续传架构:SQLite filedownlog 进度表与事务存取、FileDownloadered 下载调度器与文件名回退策略、Range 分段下载线程、DownloadProgressListener 进度回调及 MainActivity Handler 驱动,并通过真实 SQLite + 回环 HTTP 206 实测两阶段中断与续传。
学完这一章,你能够
- 系统拆解 Android 多线程断点续传架构:SQLite filedownlog 进度表与事务存取、FileDownloadered 下载调度器与文件名回退策略、Range 分段下载线程、DownloadProgressListener 进度回调及 MainActivity Handler 驱动,并通过真实 SQLite + 回环 HTTP 206 实测两阶段中断与续传。
断点续传原理与 SQLite 进度持久化层(Step 1–2)
断点续传的核心在于“以数据库持久化记录每条下载线程的已下载字节偏移”:一旦用户暂停或网络中断,下次重启只需按下载 URL 从本地库恢复各线程进度,继续通过 HTTP `Range` 请求剩余字节区间即可。Step 1 的 `DBOpenHelper.java` 创建 `downs.db` 及 `filedownlog(id, downpath, threadid, downlength)` 进度表;Step 2 的 `FileService.java` 提供按 URL 查询进度映射 `getData()`、在 SQLite 事务内批量初始化各线程记录的 `save()`、实时刷新单线程已下载长度的 `update()` 以及全文件下载完毕后清理断点记录的 `delete()`。重要代码勘误:来源 `FileService.getData()` 先调用 `cursor.moveToFirst()` 紧接着执行 `while (cursor.moveToNext())`,会导致第 1 条线程记录被跳过(遗漏 `threadid=1` 的断点);正确遍历方式是直接用 `while (cursor.moveToNext())`(因为新建 `Cursor` 初始位于第 -1 位)。
核心下载器 FileDownloadered 与分段线程 DownloadThread(Step 3–4)
Step 3 的 `FileDownloadered.java` 负责统筹资源探测、线程池调度与并发安全:内部使用 `ConcurrentHashMap<Integer, Integer>` 缓存各线程实时进度,并以 `synchronized` 修饰 `append()` 和 `update()` 保证多工作线程累加总字节数与刷库互斥;文件名解析按三级回退——先截 URL 末尾 `/` 后的文件名,其次正则匹配响应头 `Content-Disposition` 中的 `filename=`,最后生成 `UUID.randomUUID() + ".tmp"`。构造阶段若检测到 SQLite 已有同线程数的历史断点即累加初始 `downloadedSize`;若中途某条线程异常置位 `-1`,轮询循环会自动为该分块重建线程续传。Step 4 的 `DownloadThread.java` 为每条未完成线程计算精准字节范围 `startPos = block * (threadId - 1) + downLength`、`endPos = block * threadId - 1`(实际末块需夹紧至 `fileSize - 1`),发送 `Range: bytes=startPos-endPos` 并经 `RandomAccessFile.seek(startPos)` 边写边刷新数据库,同时周期检查 `downloader.getExited()` 响应停止指令。
进度监听接口、UI 布局、Handler 线程协同与权限(Step 5–8)
Step 5 定义极简回调接口 `DownloadProgressListener.onDownloadSize(int downloadedSize)` 解耦下载器与界面层;Step 6 的 `activity_main.xml` 布局提供下载地址框、下载/停止按钮(默认禁用停止按钮防止误点)、水平进度条与百分比文本;Step 7 的 `MainActivity.java` 遵循 Android 主线程 5 秒 ANR 规则,在后台 `DownloadTask` 线程启动下载,再通过 `UIHandler` 接收 `PROCESSING`/`FAILURE` 消息在主线程安全更新 `ProgressBar` 与 `Toast`;Step 8 在清单中声明 `INTERNET` 及旧版外置存储权限(现代 Android 10+ 应将文件保存在应用专属目录 `getExternalFilesDir()` 或通过 `MediaStore`/WorkManager 管理后台续传任务,亦可直接选用 OkHttp 配合成熟断点下载库减少手写并发维护成本)。来源页面的两个下载包 `MulThreadContinuableDemo.zip` 与 `MulThreadContinuableDemo2-music.zip` 已按停采规则登记在附件清单中。本站结合真实 SQLite `filedownlog` 与本地回环 HTTP 206 服务完整实测了“下载 3000 字节暂停落库 → 从断点恢复下载至 9000 字节 → 校验 SHA-256 → 清除断点记录”的全流程。
运行真实 SQLite filedownlog + 本地回环 HTTP 206 两阶段多线程断点续传实测
"""Offline Android resumable multi-thread download (SQLite filedownlog + HTTP 206 Range) verifier (Ch 93: tutorial-download2)."""
from __future__ import annotations
import hashlib
import http.client
import json
import math
import re
import sqlite3
import sys
import tempfile
import threading
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
VERSION = "CPython 3.12.14 offline Android storage/HTTP/WebView verifier (Android SDK/emulator absent)"
MEDIA_BYTES = bytes((i * 53 + 7) % 256 for i in range(9_000))
MEDIA_SHA = hashlib.sha256(MEDIA_BYTES).hexdigest()
class ResumableHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, format: str, *args) -> None:
return
def do_GET(self) -> None:
if self.path not in {"/audio/twelve.mp3", "/download"}:
self.send_response(404)
self.send_header("Content-Length", "0")
self.end_headers()
return
extra = {}
if self.path == "/download":
extra["Content-Disposition"] = 'attachment; filename="fallback_track.mp3"'
rng = self.headers.get("Range")
if rng:
m = re.match(r"bytes=(\d+)-(\d*)", rng)
if m:
start = int(m.group(1))
end = int(m.group(2)) if m.group(2) else len(MEDIA_BYTES) - 1
end = min(end, len(MEDIA_BYTES) - 1)
part = MEDIA_BYTES[start : end + 1]
self.send_response(206)
self.send_header("Content-Range", f"bytes {start}-{end}/{len(MEDIA_BYTES)}")
self.send_header("Content-Length", str(len(part)))
for k, v in extra.items():
self.send_header(k, v)
self.end_headers()
self.wfile.write(part)
return
self.send_response(200)
self.send_header("Content-Length", str(len(MEDIA_BYTES)))
for k, v in extra.items():
self.send_header(k, v)
self.end_headers()
self.wfile.write(MEDIA_BYTES)
class FileServiceDB:
"""SQLite-backed progress store equivalent to DBOpenHelper + FileService."""
def __init__(self, db_path: Path):
self.db_path = db_path
conn = sqlite3.connect(self.db_path)
try:
conn.execute(
"CREATE TABLE IF NOT EXISTS filedownlog ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"downpath VARCHAR(100), threadid INTEGER, downlength INTEGER)"
)
conn.commit()
finally:
conn.close()
def save(self, path: str, thread_map: dict[int, int]) -> None:
conn = sqlite3.connect(self.db_path)
try:
conn.execute("BEGIN")
for tid, length in thread_map.items():
conn.execute(
"INSERT INTO filedownlog(downpath, threadid, downlength) VALUES (?, ?, ?)",
(path, tid, length),
)
conn.commit()
finally:
conn.close()
def get_data(self, path: str) -> dict[int, int]:
conn = sqlite3.connect(self.db_path)
try:
rows = conn.execute(
"SELECT threadid, downlength FROM filedownlog WHERE downpath = ? ORDER BY threadid",
(path,),
).fetchall()
return {tid: length for tid, length in rows}
finally:
conn.close()
def update(self, path: str, thread_id: int, pos: int) -> None:
conn = sqlite3.connect(self.db_path)
try:
conn.execute(
"UPDATE filedownlog SET downlength = ? WHERE downpath = ? AND threadid = ?",
(pos, path, thread_id),
)
conn.commit()
finally:
conn.close()
def delete(self, path: str) -> None:
conn = sqlite3.connect(self.db_path)
try:
conn.execute("DELETE FROM filedownlog WHERE downpath = ?", (path,))
conn.commit()
finally:
conn.close()
def extract_filename(url_path: str, content_disposition: str | None) -> str:
tail = url_path.rsplit("/", 1)[-1].strip()
if tail and "." in tail:
return tail
if content_disposition:
m = re.search(r'filename="?([^";]+)"?', content_disposition, re.IGNORECASE)
if m:
return m.group(1)
return f"{uuid.uuid5(uuid.NAMESPACE_URL, url_path)}.tmp"
def main() -> None:
cases = []
server = ThreadingHTTPServer(("127.0.0.1", 0), ResumableHandler)
port = server.server_address[1]
url_path = "/audio/twelve.mp3"
full_url = f"http://127.0.0.1:{port}{url_path}"
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
with tempfile.TemporaryDirectory() as tmp:
tdir = Path(tmp)
svc = FileServiceDB(tdir / "downs.db")
save_file = tdir / "twelve.mp3"
total_size = len(MEDIA_BYTES)
n_threads = 3
block = math.ceil(total_size / n_threads) # 3000 bytes each
with save_file.open("wb") as fh:
fh.truncate(total_size)
# Phase 1: Initialize 3 threads, download first 1000 bytes of each block, then simulate pause (exited=True)
svc.save(full_url, {1: 0, 2: 0, 3: 0})
for tid in range(1, n_threads + 1):
start = block * (tid - 1)
partial_end = start + 1000 - 1
c = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
c.request("GET", url_path, headers={"Range": f"bytes={start}-{partial_end}"})
r = c.getresponse()
data = r.read()
c.close()
with save_file.open("r+b") as fh:
fh.seek(start)
fh.write(data)
svc.update(full_url, tid, len(data))
checkpoint = svc.get_data(full_url)
actual1 = {"checkpoint": checkpoint, "partial_total": sum(checkpoint.values())}
expected1 = {"checkpoint": {1: 1000, 2: 1000, 3: 1000}, "partial_total": 3000}
cases.append({
"name": "resumable_phase1_sqlite_checkpoint",
"summary": "Verify Phase-1 partial HTTP 206 download persists per-thread byte offsets in SQLite filedownlog.",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Phase 2: Resume strictly from SQLite offsets using Range: bytes=startPos-endPos and clean DB on completion
resumed = svc.get_data(full_url)
range_headers_sent = []
for tid in range(1, n_threads + 1):
done = resumed[tid]
start_pos = block * (tid - 1) + done
end_pos = min(total_size - 1, block * tid - 1)
rng_hdr = f"bytes={start_pos}-{end_pos}"
range_headers_sent.append(rng_hdr)
c = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
c.request("GET", url_path, headers={"Range": rng_hdr})
r = c.getresponse()
data = r.read()
c.close()
with save_file.open("r+b") as fh:
fh.seek(start_pos)
fh.write(data)
done += len(data)
svc.update(full_url, tid, done)
final_map = svc.get_data(full_url)
if sum(final_map.values()) == total_size:
svc.delete(full_url)
after_delete = svc.get_data(full_url)
actual2 = {
"range_headers": range_headers_sent,
"final_total": sum(final_map.values()),
"db_cleaned": after_delete == {},
"sha_matches": hashlib.sha256(save_file.read_bytes()).hexdigest() == MEDIA_SHA,
}
expected2 = {
"range_headers": ["bytes=1000-2999", "bytes=4000-5999", "bytes=7000-8999"],
"final_total": 9000,
"db_cleaned": True,
"sha_matches": True,
}
cases.append({
"name": "resumable_phase2_resume_and_cleanup",
"summary": "Verify Phase-2 resumes from SQLite offsets via Range headers, verifies SHA-256, and deletes log rows.",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: Legacy FileService.getData cursor off-by-one bug demonstration
rows = [(1, 1000), (2, 1000), (3, 1000)]
# Legacy bug: cursor.moveToFirst() followed immediately by while(cursor.moveToNext()) skips row 0!
buggy_read = rows[1:]
fixed_read = rows[:]
actual3 = {"legacy_bug_skips_thread1": len(buggy_read) == 2 and buggy_read[0][0] == 2, "fixed_reads_all_3": len(fixed_read) == 3}
expected3 = {"legacy_bug_skips_thread1": True, "fixed_reads_all_3": True}
cases.append({
"name": "cursor_off_by_one_bug_check",
"summary": "Verify why calling moveToFirst() before while(moveToNext()) drops the first thread record.",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: Filename resolution priority (URL path -> Content-Disposition -> UUID .tmp)
fn_url = extract_filename("/audio/twelve.mp3", None)
fn_disp = extract_filename("/download", 'attachment; filename="fallback_track.mp3"')
fn_uuid = extract_filename("/download", None)
actual4 = {
"from_url": fn_url,
"from_content_disposition": fn_disp,
"from_uuid_fallback_ends_tmp": fn_uuid.endswith(".tmp"),
}
expected4 = {
"from_url": "twelve.mp3",
"from_content_disposition": "fallback_track.mp3",
"from_uuid_fallback_ends_tmp": True,
}
cases.append({
"name": "filename_extraction_fallback",
"summary": "Verify filename resolution order: URL tail -> Content-Disposition header -> UUID.tmp fallback.",
"expected": expected4,
"actual": actual4,
"passed": actual4 == expected4,
})
finally:
server.shutdown()
server.server_close()
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
sys.exit(main())
- 验证阶段一暂停落库 3000 字节、阶段二按 Range 续传完成 9000 字节并校验 SHA-256 与清库、Cursor 错位 bug 核对及三级文件名回退。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:d4baf5d69916f52c2a446bab95236b183df4602e90e7e376fddb35118cd9829c
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:8381252e59c69934b422964dab4342d2d1330e77863a2dd9df212c43c29e43b4
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在断点续传的 FileService.getData() 中,为什么先调 cursor.moveToFirst() 再写 while (cursor.moveToNext()) 会导致断点恢复不完整?
展开参考解答
Android 查询返回的 Cursor 初始指向第 -1 位置;先调 moveToFirst() 会把游标移到第 0 行,紧接着 while(cursor.moveToNext()) 在读取前又推进到第 1 行,从而永久跳过了第一条线程的已下载进度记录。