修复传输问题

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
@@ -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