修复传输问题

This commit is contained in:
zhy200308
2026-08-11 09:44:26 +08:00
parent 4d77ba6c91
commit b444a39a63
5 changed files with 320 additions and 124 deletions
@@ -25,6 +25,11 @@ object DownloadClient {
private const val TAG = "QftDownload"
private const val BUFFER_SIZE = 1024 * 1024
private const val ATTEMPTS = 5
/** 整份重下的轮数。仅在 SHA-256 不匹配(缓存已损坏)时才会用到第二轮。 */
private const val VERIFY_ROUNDS = 2
/** 落盘阶段的失败与「下载失败」是两回事,用独立异常类型区分。 */
class SaveFailure(message: String, cause: Throwable?) : Exception(message, cause)
fun download(
context: Context,
@@ -33,6 +38,11 @@ object DownloadClient {
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
/** 返回非 null 表示应立刻中止(例如 QFT 临时网络已断开),并以该原因报错。 */
abortReason: () -> String? = { null },
/** 阶段提示。传输完成后还有校验与落盘两步,必须让 UI 有反馈,
* 否则用户看到的就是「进度条停在 100% 然后报错」。 */
onPhase: (String) -> Unit = {},
onProgress: (received: Long, total: Long) -> Unit,
): DownloadedFile {
require(pairing.direction == TransferDirection.DOWNLOAD_TO_PHONE)
@@ -43,24 +53,68 @@ object DownloadClient {
partial.parentFile?.let { if (!it.exists() && !it.mkdirs()) error("无法创建接收缓存目录") }
if (partial.length() > expectedSize) partial.delete()
// 落盘时缓存文件与目标文件同时存在,需要约 2 倍空间。
// 不预检的话,这里会在下载 100% 之后才失败,用户看到的是「快结束时失败」。
ensureSpaceForTransfer(partial, expectedSize)
repeat(VERIFY_ROUNDS) { round ->
receiveUntilComplete(network, baseUrl, pairing, deviceName, partial,
expectedSize, abortReason, onProgress)
onPhase("正在校验文件完整性…")
val actual = sha256(partial, onProgress)
if (actual.equals(expectedSha, ignoreCase = true)) {
onPhase("正在保存到 Downloads/QFT…")
ensureSpaceForSave(partial, expectedSize)
val result = try {
saveToDownloads(resolver, partial, expectedName, expectedSize, onProgress)
} catch (e: Exception) {
// 这一步失败与网络无关,重下多少次都没用,直接如实报错
throw SaveFailure("文件已完整收到,但保存到 Downloads/QFT 失败:${failureDetail(e)}", e)
}
partial.delete()
Log.i(TAG, "completed size=$expectedSize")
return result
}
Log.w(TAG, "sha mismatch round=${round + 1}/$VERIFY_ROUNDS expected=$expectedSha actual=$actual")
partial.delete()
if (round + 1 >= VERIFY_ROUNDS) {
error("文件校验失败:重新完整下载后 SHA-256 仍不匹配,请让电脑重新生成二维码")
}
onPhase("校验未通过,正在重新完整下载…")
}
error("下载未能完成")
}
/** 传输阶段:断点续传 + 有限重试。只有这一段的失败才算「下载失败」。 */
private fun receiveUntilComplete(
network: Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
partial: File,
expectedSize: Long,
abortReason: () -> String?,
onProgress: (received: Long, total: Long) -> Unit,
) {
var last: Exception? = null
repeat(ATTEMPTS) { attempt ->
abortReason()?.let { throw IllegalStateException(it, last) }
try {
Log.i(TAG, "attempt=${attempt + 1}/$ATTEMPTS partial=${partial.length()}/$expectedSize endpoint=$baseUrl")
if (partial.length() < expectedSize) {
receiveAttempt(network, baseUrl, pairing, deviceName, partial, expectedSize, onProgress)
receiveAttempt(network, baseUrl, pairing, deviceName, partial,
expectedSize, abortReason, onProgress)
}
if (partial.length() != expectedSize) {
error("下载提前结束:${partial.length()}/$expectedSize")
}
verifySha256(partial, expectedSha)
val result = saveToDownloads(resolver, partial, expectedName, expectedSize)
partial.delete()
Log.i(TAG, "completed size=$expectedSize")
return result
return
} catch (e: Exception) {
last = e
Log.w(TAG, "attempt=${attempt + 1}/$ATTEMPTS failed partial=${partial.length()}/$expectedSize: ${failureDetail(e)}", e)
abortReason()?.let { throw IllegalStateException(it, e) }
if (attempt + 1 < ATTEMPTS) {
try {
Thread.sleep(250L * (attempt + 1))
@@ -71,7 +125,28 @@ object DownloadClient {
}
}
}
throw IllegalStateException("从电脑下载失败,已重试 $ATTEMPTS 次:${failureDetail(last)}", last)
val progressed = partial.length()
throw IllegalStateException(
"从电脑下载失败,已重试 $ATTEMPTS 次(已收到 ${progressed}/$expectedSize 字节):${failureDetail(last)}",
last,
)
}
/** 传输 + 落盘阶段合计需要的可用空间。 */
private fun ensureSpaceForTransfer(partial: File, expectedSize: Long) {
val root = partial.parentFile ?: return
val needed = (expectedSize - partial.length()).coerceAtLeast(0L) + expectedSize
val usable = root.usableSpace
if (usable in 1 until needed) {
error("存储空间不足:本次接收约需 ${needed / 1024 / 1024} MB(含保存时的临时副本),当前可用 ${usable / 1024 / 1024} MB")
}
}
private fun ensureSpaceForSave(partial: File, expectedSize: Long) {
val usable = partial.parentFile?.usableSpace ?: return
if (usable in 1 until expectedSize) {
error("存储空间不足:保存副本还需 ${expectedSize / 1024 / 1024} MB,当前可用 ${usable / 1024 / 1024} MB")
}
}
private fun receiveAttempt(
@@ -81,6 +156,7 @@ object DownloadClient {
deviceName: String,
partial: File,
expectedSize: Long,
abortReason: () -> String?,
onProgress: (received: Long, total: Long) -> Unit,
) {
val requestedOffset = partial.length().coerceIn(0L, expectedSize)
@@ -132,6 +208,9 @@ object DownloadClient {
FileOutputStream(partial, offset > 0L).use { output ->
val buffer = ByteArray(BUFFER_SIZE)
while (true) {
// 网络已断开时立刻收手:否则会在 readTimeout 上白等 12 秒,
// 再乘以 5 次重试,用户等一分钟才看到错误。
abortReason()?.let { error(it) }
val n = input.read(buffer)
if (n < 0) break
if (n == 0) continue
@@ -154,21 +233,30 @@ object DownloadClient {
}
}
private fun verifySha256(file: File, expectedSha: String) {
/** 校验也要报进度:大文件读一整遍是好几秒,静默的话看起来就是卡在 100%。 */
private fun sha256(file: File, onProgress: (Long, Long) -> Unit): String {
val digest = MessageDigest.getInstance("SHA-256")
val total = file.length()
var done = 0L
var lastReport = 0L
FileInputStream(file).use { input ->
val buffer = ByteArray(BUFFER_SIZE)
while (true) {
val n = input.read(buffer)
if (n < 0) break
if (n > 0) digest.update(buffer, 0, n)
if (n > 0) {
digest.update(buffer, 0, n)
done += n.toLong()
val now = android.os.SystemClock.elapsedRealtime()
if (now - lastReport >= 80L) {
onProgress(done, total)
lastReport = now
}
}
}
}
val actual = digest.digest().toHex()
if (!actual.equals(expectedSha, ignoreCase = true)) {
file.delete()
error("文件校验失败,已清除不完整缓存;请重试")
}
onProgress(total, total)
return digest.digest().toHex()
}
private fun saveToDownloads(
@@ -176,6 +264,7 @@ object DownloadClient {
partial: File,
expectedName: String,
expectedSize: Long,
onProgress: (Long, Long) -> Unit,
): DownloadedFile {
var target: DownloadTarget? = null
try {
@@ -185,12 +274,18 @@ object DownloadClient {
createdTarget.output.use { output ->
val buffer = ByteArray(BUFFER_SIZE)
var copied = 0L
var lastReport = 0L
while (true) {
val n = input.read(buffer)
if (n < 0) break
if (n == 0) continue
output.write(buffer, 0, n)
copied += n.toLong()
val now = android.os.SystemClock.elapsedRealtime()
if (now - lastReport >= 80L) {
onProgress(copied, expectedSize)
lastReport = now
}
}
output.flush()
if (copied != expectedSize) error("保存下载文件时大小发生变化")
@@ -86,6 +86,9 @@ class MainActivity : ComponentActivity() {
private var connectingStatusText: TextView? = null
private var downloadStatusText: TextView? = null
@Volatile private var downloadRunning = false
/** 非 null 表示当前传输应立刻中止(QFT 临时网络断开等)。
* 下载线程每读一个缓冲区就检查一次,避免在 readTimeout 上白等。 */
@Volatile private var transferAbortReason: String? = null
@Volatile private var pairConnectionAttempt = 0L
private val requestCamera = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
@@ -643,6 +646,10 @@ class MainActivity : ComponentActivity() {
// HTTP/timeout cause instead of replacing it with this generic
// message mid-retry.
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE && downloadRunning) {
// 让下载线程立刻收手并如实报告断网,而不是继续跑完
// 5 次「重试 → 12 秒超时」,最后给出一个与真因无关的
// 「下载失败,已重试 N 次」。
transferAbortReason = message
downloadStatusText?.apply {
text = "QFT 本地网络已断开,正在结束当前下载请求…"
setTextColor(WARNING)
@@ -765,9 +772,13 @@ class MainActivity : ComponentActivity() {
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
downloadRunning = true
transferAbortReason = null
transferExecutor.execute {
// 「传输 / 校验 / 保存」三个阶段各自的速率含义不同,
// 每进入一个新阶段就重新计时,否则显示出来的速率毫无意义。
var phaseLabel = "正在接收"
var phaseStartedAt = android.os.SystemClock.elapsedRealtime()
try {
val startedAt = android.os.SystemClock.elapsedRealtime()
val saved = DownloadClient.download(
context = this@MainActivity,
resolver = contentResolver,
@@ -775,13 +786,19 @@ class MainActivity : ComponentActivity() {
baseUrl = baseUrl,
pairing = pair,
deviceName = receiverDeviceLabel,
abortReason = { transferAbortReason },
onPhase = { label ->
phaseLabel = label
phaseStartedAt = android.os.SystemClock.elapsedRealtime()
runOnUiThread { status.text = label }
},
) { received, expected ->
runOnUiThread {
val fraction = if (expected <= 0) 0 else ((received * 1000L) / expected).toInt().coerceIn(0, 1000)
val elapsed = (android.os.SystemClock.elapsedRealtime() - startedAt).coerceAtLeast(1L)
val elapsed = (android.os.SystemClock.elapsedRealtime() - phaseStartedAt).coerceAtLeast(1L)
val rate = received * 1000.0 / elapsed
bar.progress = fraction
status.text = "${humanBytes(received)} / ${humanBytes(expected)} · ${humanBytes(rate.toLong())}/s"
status.text = "$phaseLabel ${humanBytes(received)} / ${humanBytes(expected)} · ${humanBytes(rate.toLong())}/s"
}
}
runOnUiThread {
@@ -792,7 +809,9 @@ class MainActivity : ComponentActivity() {
} catch (e: Exception) {
runOnUiThread {
downloadRunning = false
showPairError(pair, "从电脑接收失败:${e.message}")
// 落盘失败时文件其实已经完整收到了,别再说「接收失败」误导用户
val prefix = if (e is DownloadClient.SaveFailure) "保存失败" else "从电脑接收失败"
showPairError(pair, "$prefix:${e.message}")
}
} finally {
downloadRunning = false
@@ -30,49 +30,79 @@ class WifiConnector(context: Context) {
private var legacyPreviousNetworkId: Int? = null
private var legacyTargetNetworkId: Int? = null
/**
* 回调经由这个可替换的收件人转发,而不是被 NetworkCallback 闭包捕获。
* 这样「用户点重试」时可以直接换掉 UI 回调、继续复用那个还挂着的
* WifiNetworkSpecifier 请求,不必 unregister —— 在系统选网弹窗还开着的
* 时候 unregister,Android 会弹「该应用已取消选择设备的请求」。
*/
private class Listener(
val onStatus: (String) -> Unit,
val onAvailable: (Network?) -> Unit,
val onUnavailable: (String) -> Unit,
)
private var listener: Listener? = null
private var pendingSsid: String? = null
private var pendingDelivered: AtomicBoolean? = null
private var pendingTerminal: AtomicBoolean? = null
private var pendingStartedAt = 0L
// 所有对外回调都只走这三个入口。直接调用捕获来的闭包会在「复用挂起请求」
// 时通知到上一次的界面,是很难查的一类 bug。
private fun notifyStatus(message: String) { listener?.onStatus?.invoke(message) }
private fun notifyAvailable(network: Network?) { listener?.onAvailable?.invoke(network) }
private fun notifyUnavailable(message: String) { listener?.onUnavailable?.invoke(message) }
fun connect(
pairing: PairingPayload,
onStatus: (String) -> Unit,
onAvailable: (Network?) -> Unit,
onUnavailable: (String) -> Unit,
) {
val wifi = pairing.wifi
// 同一个 SSID 的请求还挂在系统那里且没有终结:换掉 UI 回调即可,
// 千万不要 unregister 再重新 requestNetwork。
if (wifi != null && callback != null && pendingSsid == wifi.ssid &&
pendingTerminal?.get() == false && pendingDelivered?.get() == false) {
Log.i(TAG, "reuse outstanding request SSID=${wifi.ssid}")
listener = Listener(onStatus, onAvailable, onUnavailable)
notifyStatus("系统配网请求仍在进行中,正在继续等待…")
scheduleWaitHints(generation, wifi.ssid)
return
}
release(restoreLegacy = false)
generation++
val run = generation
val wifi = pairing.wifi
listener = Listener(onStatus, onAvailable, onUnavailable)
if (wifi == null) {
onStatus("正在使用当前局域网发现电脑…")
notifyStatus("正在使用当前局域网发现电脑…")
val wifiNetwork = bestWifiNetwork()
onAvailable(wifiNetwork ?: connectivity.activeNetwork)
notifyAvailable(wifiNetwork ?: connectivity.activeNetwork)
return
}
if (Build.VERSION.SDK_INT >= 29) {
connectModern(run, wifi, onStatus, onAvailable, onUnavailable)
connectModern(run, wifi)
} else {
connectLegacy(run, wifi, onStatus, onAvailable, onUnavailable)
connectLegacy(run, wifi)
}
}
@RequiresApi(29)
@Suppress("MissingPermission")
private fun connectModern(
run: Int,
wifi: WifiCredentials,
onStatus: (String) -> Unit,
onAvailable: (Network?) -> Unit,
onUnavailable: (String) -> Unit,
) {
onStatus("正在请求连接 ${wifi.ssid}…")
private fun connectModern(run: Int, wifi: WifiCredentials) {
Log.i(TAG, "attempt=$run request SSID=${wifi.ssid}")
onStatus("正在等待 Android 系统连接确认;确认后本页将继续显示进度")
notifyStatus("正在等待 Android 系统连接确认;确认后本页将继续显示进度")
val specifier = try {
WifiNetworkSpecifier.Builder()
.setSsid(wifi.ssid)
.setWpa2Passphrase(wifi.passphrase)
.build()
} catch (e: Exception) {
onUnavailable("配网参数无效:${e.message}")
notifyUnavailable("配网参数无效:${e.message}")
return
}
val request = NetworkRequest.Builder()
@@ -86,16 +116,22 @@ class WifiConnector(context: Context) {
// launching a duplicate probe/download for the same Wi-Fi connection.
val delivered = AtomicBoolean(false)
val terminal = AtomicBoolean(false)
pendingSsid = wifi.ssid
pendingDelivered = delivered
pendingTerminal = terminal
pendingStartedAt = SystemClock.elapsedRealtime()
val startedAt = pendingStartedAt
val cb = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
if (run != generation || terminal.get()) return
Log.i(TAG, "attempt=$run framework onAvailable network=$network")
onStatus("Wi-Fi 已关联,正在等待本地 IP/路由…")
waitUntilUsable(run, network, onStatus) {
notifyStatus("Wi-Fi 已关联,正在等待本地 IP/路由…")
waitUntilUsable(run, network, ::notifyStatus) {
if (run == generation && !terminal.get() && delivered.compareAndSet(false, true)) {
Log.i(TAG, "attempt=$run route ready network=$network")
onStatus("QFT 本地网络已就绪,正在快速发现电脑…")
onAvailable(network)
notifyStatus("QFT 本地网络已就绪,正在快速发现电脑…")
notifyAvailable(network)
}
}
}
@@ -104,21 +140,33 @@ class WifiConnector(context: Context) {
if (run != generation || terminal.get() || delivered.get()) return
if (hasIpv4(linkProperties) && delivered.compareAndSet(false, true)) {
Log.i(TAG, "attempt=$run IPv4 ready network=$network")
onStatus("QFT 本地网络已就绪,正在快速发现电脑…")
onAvailable(network)
notifyStatus("QFT 本地网络已就绪,正在快速发现电脑…")
notifyAvailable(network)
}
}
override fun onUnavailable() {
if (run != generation || !terminal.compareAndSet(false, true)) return
Log.w(TAG, "attempt=$run framework onUnavailable")
if (run == generation) onUnavailable("未能连接 QFT 临时网络。请确认 Wi-Fi 已开启并批准系统连接请求。")
val waited = SystemClock.elapsedRealtime() - startedAt
Log.w(TAG, "attempt=$run framework onUnavailable after ${waited}ms")
// Android 不区分「用户点了取消」和「始终没扫到这个热点」,
// 只能用等待时长推断,给出真正能指导用户下一步的提示。
notifyUnavailable(
if (waited < 4_000L) {
"已取消系统配网。请重新点击「重试连接」,并在系统弹窗里选择 ${wifi.ssid} 后点连接。"
} else {
"系统始终没有搜索到热点 ${wifi.ssid}。请确认:" +
"① 电脑上 QFT 接收页仍开着且显示 Direct 已启动;" +
"② 手机 Wi-Fi 列表里能看到这个名字;" +
"③ 电脑与手机距离不要太远。"
}
)
}
override fun onLost(network: Network) {
if (run != generation || !delivered.get() || !terminal.compareAndSet(false, true)) return
Log.w(TAG, "attempt=$run network lost network=$network")
if (run == generation && delivered.get()) onUnavailable("QFT 临时网络已断开")
notifyUnavailable("QFT 临时网络已断开")
}
}
callback = cb
@@ -130,26 +178,37 @@ class WifiConnector(context: Context) {
// system sheet; otherwise keep this request alive while our page
// continues to show connection progress.
connectivity.requestNetwork(request, cb)
handler.postDelayed({
if (run == generation && !terminal.get() && !delivered.get()) {
onStatus("仍在等待系统完成配网…")
}
}, 8_000)
scheduleWaitHints(run, wifi.ssid)
} catch (e: Exception) {
callback = null
onUnavailable("系统配网请求失败:${e.message}")
pendingSsid = null
notifyUnavailable("系统配网请求失败:${e.message}")
}
}
/**
* 弹窗久久不出结果时逐级给出更具体的提示。
* 截图里那种「弹窗一直转圈」的情况,光说「仍在等待系统完成配网」
* 完全没有指导意义——真正的原因通常是电脑侧热点没起来。
*/
private fun scheduleWaitHints(run: Int, ssid: String) {
fun pending(): Boolean =
run == generation && pendingTerminal?.get() == false && pendingDelivered?.get() == false
handler.postDelayed({
if (pending()) listener?.onStatus?.invoke("仍在等待系统完成配网…")
}, 8_000)
handler.postDelayed({
if (pending()) listener?.onStatus?.invoke(
"系统仍在搜索 $ssid。若弹窗里一直没出现这个名字," +
"多半是电脑侧热点没启动——请检查 Windows 上 QFT 接收页是否显示 Direct 已就绪。"
)
}, 20_000)
}
@Suppress("DEPRECATION", "MissingPermission")
private fun connectLegacy(
run: Int,
wifi: WifiCredentials,
onStatus: (String) -> Unit,
onAvailable: (Network?) -> Unit,
onUnavailable: (String) -> Unit,
) {
onStatus("Android ${Build.VERSION.RELEASE} 兼容配网:正在连接 ${wifi.ssid}…")
private fun connectLegacy(run: Int, wifi: WifiCredentials) {
notifyStatus("Android ${Build.VERSION.RELEASE} 兼容配网:正在连接 ${wifi.ssid}…")
try {
if (!wifiManager.isWifiEnabled) {
wifiManager.isWifiEnabled = true
@@ -168,13 +227,13 @@ class WifiConnector(context: Context) {
wifiManager.addNetwork(config)
}
if (targetId < 0) {
onUnavailable("Android 7~9 无法写入 QFT Wi-Fi 配置;请确认已授予位置权限。")
notifyUnavailable("Android 7~9 无法写入 QFT Wi-Fi 配置;请确认已授予位置权限。")
return
}
legacyTargetNetworkId = targetId
wifiManager.disconnect()
if (!wifiManager.enableNetwork(targetId, true)) {
onUnavailable("系统拒绝启用 QFT Wi-Fi 网络")
notifyUnavailable("系统拒绝启用 QFT Wi-Fi 网络")
return
}
wifiManager.reconnect()
@@ -186,20 +245,20 @@ class WifiConnector(context: Context) {
if (matches) {
val network = bestWifiNetwork()
if (network != null && hasIpv4(connectivity.getLinkProperties(network))) {
onStatus("QFT Wi-Fi 已连接,正在快速发现电脑…")
onAvailable(network)
notifyStatus("QFT Wi-Fi 已连接,正在快速发现电脑…")
notifyAvailable(network)
return
}
}
if (SystemClock.elapsedRealtime() - started > 15_000) {
onUnavailable("连接 QFT Wi-Fi 超时。请确认电脑热点仍在运行。")
notifyUnavailable("连接 QFT Wi-Fi 超时。请确认电脑热点仍在运行。")
} else {
handler.postDelayed({ poll() }, 250)
}
}
handler.postDelayed({ poll() }, 250)
} catch (e: Exception) {
onUnavailable("Android 7~9 配网失败:${e.message}")
notifyUnavailable("Android 7~9 配网失败:${e.message}")
}
}
@@ -316,6 +375,10 @@ class WifiConnector(context: Context) {
try { connectivity.unregisterNetworkCallback(it) } catch (_: Exception) {}
}
callback = null
listener = null
pendingSsid = null
pendingDelivered = null
pendingTerminal = null
handler.removeCallbacksAndMessages(null)
if (restoreLegacy && Build.VERSION.SDK_INT < 29) {
val previous = legacyPreviousNetworkId