From 2ff0741fffda32a8f616bc3287063a9306223a4d Mon Sep 17 00:00:00 2001 From: zhy200308 <2258391712@qq.com> Date: Wed, 12 Aug 2026 16:27:02 +0800 Subject: [PATCH] fix: connect older Android receivers to phone hotspots --- README.md | 4 +- android/app/build.gradle.kts | 4 +- .../main/java/com/qft/optical/MainActivity.kt | 33 ++++- .../java/com/qft/optical/WifiConnector.kt | 131 +++++++++++++----- docs/ANDROID_PHONE_TRANSFER.md | 8 +- docs/PROTOCOL.md | 2 +- scripts/android_compat_selftest.py | 5 + 7 files changed, 139 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index e16cd22..3e1b094 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ v0.4.16 提供两套互不依赖的传输方式: > v0.4.16 已完成协议、图像合成解码、ROI、双向并发传输、专用 Wi-Fi 快速发现、队列拖动稳定性和关键 Kotlin 源码测试。当前生成环境没有真实 Windows 显示器、Android 相机或 Wi‑Fi Direct 适配器,因此物理 30/45/60 FPS 和真实扫码配网仍需在你的设备上跑 `VERIFY_WINDOWS_HOST.ps1` 后做最终验收;详见 `TEST_REPORT.md`。 -## v0.5.0-dev2:Android → Android 手机互传 +## v0.5.0-dev3:Android → Android 手机互传 当前开发版新增 Android 手机之间的扫码直传闭环: @@ -27,6 +27,8 @@ v0.4.16 提供两套互不依赖的传输方式: - 每个文件复用现有最高 8 路 HTTP Range、断点位图和 SHA-256 校验,按发送队列顺序保存到 `Downloads/QFT`; - 发送页面必须保持打开,返回首页会立即关闭发送服务和临时热点。 - 发送二维码按当前应用窗口的实际可用宽高动态生成并居中,手机、平板和分屏窗口都不会再被 `match_parent` 放大溢出。 +- Android 7–9 接收端每次扫码都会用二维码中的新密码刷新临时 Wi-Fi 配置,不再复用同名热点的旧密码;Android 10+ 也只复用完整凭据一致的系统配网请求。 +- 当高版本发送机只能创建旧设备不支持的纯 WPA3 热点时,接收端会跳过无效的系统搜索,并自动尝试二维码内经过认证的原局域网地址。 此阶段只实现 Android → Android;Android ↔ iOS 尚未接入。 diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index dd1a542..180f805 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -12,8 +12,8 @@ android { applicationId = "com.qft.optical" minSdk = 24 targetSdk = 35 - versionCode = 25 - versionName = "0.5.0-dev2" + versionCode = 26 + versionName = "0.5.0-dev3" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } diff --git a/android/app/src/main/java/com/qft/optical/MainActivity.kt b/android/app/src/main/java/com/qft/optical/MainActivity.kt index 118d640..9ae1a46 100644 --- a/android/app/src/main/java/com/qft/optical/MainActivity.kt +++ b/android/app/src/main/java/com/qft/optical/MainActivity.kt @@ -228,7 +228,7 @@ class MainActivity : ComponentActivity() { ) { showReceivedFiles() }) root.addView(space(22)) root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED)) - root.addView(text("QFT v0.5.0-dev2 · Android 7+ 到最新", 12f, MUTED)) + root.addView(text("QFT v0.5.0-dev3 · Android 7+ 到最新", 12f, MUTED)) setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) }) } @@ -639,14 +639,33 @@ class MainActivity : ComponentActivity() { val attempt = ++pairConnectionAttempt transferAbortReason = null connectedBaseUrl = null - // 携带 Wi-Fi 身份的 QFT Direct 会无条件先连接那张专用网络。 - // 不再尝试二维码/电脑当前 LAN 地址;“当前局域网”仍是桌面端用户 - // 明确选择的独立备用模式(wifi == null)。 - connectViaWifi(pair, attempt) + val unsupportedHotspot = pair.direction == TransferDirection.PHONE_TO_PHONE && + pair.wifi?.let { !wifiConnector.canJoinAutomatically(it) } == true + val effectivePair = if (unsupportedHotspot && pair.endpoints.isNotEmpty()) { + // A high-version sender/OEM may create a pure WPA3 LocalOnlyHotspot, + // which an old receiver physically cannot join. The QR also carries + // authenticated private LAN endpoints, so try those automatically + // instead of leaving the system Wi-Fi sheet searching forever. + pair.copy(wifi = null) + } else pair + // 携带可兼容 Wi-Fi 身份的 QFT Direct 会先连接专用网络;唯一例外是 + // 接收硬件不支持二维码声明的纯 WPA3,此时才自动回落到经过同网段 + // 过滤和会话认证的原局域网地址。 + connectViaWifi( + effectivePair, + attempt, + if (unsupportedHotspot && effectivePair.wifi == null) { + "发送热点为 WPA3,当前旧设备不支持;正在自动尝试两机原有局域网…" + } else null, + ) } - private fun connectViaWifi(pair: PairingPayload, attempt: Long) { - showConnecting(pair, pair.wifi?.let { "正在请求连接 ${it.ssid}…" } ?: "正在使用当前局域网探测电脑…") + private fun connectViaWifi(pair: PairingPayload, attempt: Long, initialMessage: String? = null) { + showConnecting( + pair, + initialMessage ?: pair.wifi?.let { "正在请求连接 ${it.ssid}…" } + ?: "正在使用当前局域网探测发送设备…", + ) wifiConnector.connect( pairing = pair, onStatus = { message -> runOnUiThread { diff --git a/android/app/src/main/java/com/qft/optical/WifiConnector.kt b/android/app/src/main/java/com/qft/optical/WifiConnector.kt index 04d3a10..4b86839 100644 --- a/android/app/src/main/java/com/qft/optical/WifiConnector.kt +++ b/android/app/src/main/java/com/qft/optical/WifiConnector.kt @@ -48,7 +48,9 @@ class WifiConnector(context: Context) { ) private var listener: Listener? = null - private var pendingSsid: String? = null + /** The whole credential tuple owns a modern request. LocalOnlyHotspot may + * reuse its SSID while rotating the passphrase between reservations. */ + private var pendingWifi: WifiCredentials? = null private var pendingDelivered: AtomicBoolean? = null private var pendingTerminal: AtomicBoolean? = null private var pendingStartedAt = 0L @@ -59,6 +61,12 @@ class WifiConnector(context: Context) { private fun notifyAvailable(network: Network?) { listener?.onAvailable?.invoke(network) } private fun notifyUnavailable(message: String) { listener?.onUnavailable?.invoke(message) } + /** Pure WPA3 hotspots cannot be joined by Android 7–9, or by Android 10+ + * devices whose Wi-Fi chipset does not expose SAE support. */ + fun canJoinAutomatically(wifi: WifiCredentials): Boolean = + wifi.security != "WPA3" || + (Build.VERSION.SDK_INT >= 29 && wifiManager.isWpa3SaeSupported) + fun connect( pairing: PairingPayload, onStatus: (String) -> Unit, @@ -75,7 +83,7 @@ class WifiConnector(context: Context) { // 「配网越来越慢、几分钟都没反应」。超窗就推倒重来。 val reusable = pendingStartedAt > 0L && SystemClock.elapsedRealtime() - pendingStartedAt < REUSE_WINDOW_MS - if (wifi != null && callback != null && pendingSsid == wifi.ssid && reusable && + if (wifi != null && callback != null && pendingWifi == wifi && reusable && pendingTerminal?.get() == false) { Log.i(TAG, "reuse outstanding request SSID=${wifi.ssid}") listener = Listener(onStatus, onAvailable, onUnavailable) @@ -85,7 +93,7 @@ class WifiConnector(context: Context) { notifyAvailable(active) } else { notifyStatus("系统配网请求仍在进行中,正在自动恢复连接…") - scheduleWaitHints(generation, wifi.ssid) + scheduleWaitHints(generation, wifi.ssid, pairing.direction) } return } @@ -95,7 +103,7 @@ class WifiConnector(context: Context) { val run = generation listener = Listener(onStatus, onAvailable, onUnavailable) if (wifi == null) { - notifyStatus("正在使用当前局域网发现电脑…") + notifyStatus("正在使用当前局域网发现发送设备…") val wifiNetwork = bestWifiNetwork() currentNetwork = wifiNetwork ?: connectivity.activeNetwork notifyAvailable(currentNetwork) @@ -103,7 +111,7 @@ class WifiConnector(context: Context) { } if (Build.VERSION.SDK_INT >= 29) { - connectModern(run, wifi) + connectModern(run, wifi, pairing.direction) } else { connectLegacy(run, wifi) } @@ -111,7 +119,7 @@ class WifiConnector(context: Context) { @RequiresApi(29) @Suppress("MissingPermission") - private fun connectModern(run: Int, wifi: WifiCredentials) { + private fun connectModern(run: Int, wifi: WifiCredentials, direction: TransferDirection) { Log.i(TAG, "attempt=$run request SSID=${wifi.ssid}") // Ask the radio for a fresh scan immediately before presenting the // NetworkSpecifier chooser. Some OEMs otherwise reuse an old scan cache @@ -149,7 +157,7 @@ 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 + pendingWifi = wifi pendingDelivered = delivered pendingTerminal = terminal pendingStartedAt = SystemClock.elapsedRealtime() @@ -192,10 +200,17 @@ class WifiConnector(context: Context) { if (waited < 4_000L) { "已取消系统配网。请重新点击「重试连接」,并在系统弹窗里选择 ${wifi.ssid} 后点连接。" } else { - "系统始终没有搜索到热点 ${wifi.ssid}。请确认:" + - "① 电脑上 QFT 接收页仍开着且显示 Direct 已启动;" + - "② 手机 Wi-Fi 列表里能看到这个名字;" + - "③ 电脑与手机距离不要太远。" + if (direction == TransferDirection.PHONE_TO_PHONE) { + "系统始终没有搜索到热点 ${wifi.ssid}。请确认:" + + "① 发送手机仍停留在二维码页面;" + + "② 两台手机距离不要太远;" + + "③ 发送手机没有关闭临时热点或进入省电状态。" + } else { + "系统始终没有搜索到热点 ${wifi.ssid}。请确认:" + + "① 电脑上 QFT 接收页仍开着且显示 Direct 已启动;" + + "② 手机 Wi-Fi 列表里能看到这个名字;" + + "③ 电脑与手机距离不要太远。" + } } ) } @@ -220,10 +235,10 @@ class WifiConnector(context: Context) { // system sheet; otherwise keep this request alive while our page // continues to show connection progress. connectivity.requestNetwork(request, cb) - scheduleWaitHints(run, wifi.ssid) + scheduleWaitHints(run, wifi.ssid, direction) } catch (e: Exception) { callback = null - pendingSsid = null + pendingWifi = null notifyUnavailable("系统配网请求失败:${e.message}") } } @@ -233,7 +248,7 @@ class WifiConnector(context: Context) { * 截图里那种「弹窗一直转圈」的情况,光说「仍在等待系统完成配网」 * 完全没有指导意义——真正的原因通常是电脑侧热点没起来。 */ - private fun scheduleWaitHints(run: Int, ssid: String) { + private fun scheduleWaitHints(run: Int, ssid: String, direction: TransferDirection) { fun pending(): Boolean = run == generation && pendingTerminal?.get() == false && pendingDelivered?.get() == false @@ -241,10 +256,14 @@ class WifiConnector(context: Context) { if (pending()) listener?.onStatus?.invoke("仍在等待系统完成配网…") }, 4_000) handler.postDelayed({ - if (pending()) listener?.onStatus?.invoke( - "系统仍在搜索 $ssid。若弹窗里一直没出现这个名字," + - "多半是电脑侧热点没启动——请检查 Windows 上 QFT 接收页是否显示 Direct 已就绪。" - ) + if (pending()) { + val peerHint = if (direction == TransferDirection.PHONE_TO_PHONE) { + "请确认发送手机仍停留在二维码页面,且临时热点没有被省电模式关闭。" + } else { + "请检查 Windows 上 QFT 接收页是否显示 Direct 已就绪。" + } + listener?.onStatus?.invoke("系统仍在搜索 $ssid。若弹窗里没有这个名字,$peerHint") + } }, 20_000) } @@ -261,22 +280,41 @@ class WifiConnector(context: Context) { } legacyPreviousNetworkId = wifiManager.connectionInfo?.networkId?.takeIf { it >= 0 } val quoted = "\"${wifi.ssid}\"" - val existing = try { wifiManager.configuredNetworks?.firstOrNull { it.SSID == quoted } } catch (_: Exception) { null } - val targetId = if (existing != null) { - existing.networkId - } else { - val config = WifiConfiguration().apply { - SSID = quoted - preSharedKey = "\"${wifi.passphrase}\"" - allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK) - } - wifiManager.addNetwork(config) + val existing = try { + wifiManager.configuredNetworks?.firstOrNull { normalizeSsid(it.SSID) == wifi.ssid } + } catch (_: Exception) { null } + val config = WifiConfiguration().apply { + SSID = quoted + preSharedKey = "\"${wifi.passphrase}\"" + hiddenSSID = false + status = WifiConfiguration.Status.ENABLED + allowedKeyManagement.clear() + allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK) } + // A LocalOnlyHotspot reservation may keep the same generated SSID + // but rotate its password. Reusing an old WifiConfiguration without + // replacing the PSK leaves Android 7–9 in an endless association + // loop. Always update the saved entry from the freshly scanned QR. + var targetId = if (existing != null) { + config.networkId = existing.networkId + wifiManager.updateNetwork(config) + } else -1 if (targetId < 0) { - notifyUnavailable("Android 7~9 无法写入 QFT Wi-Fi 配置;请确认已授予位置权限。") + existing?.let { wifiManager.removeNetwork(it.networkId) } + config.networkId = -1 + targetId = wifiManager.addNetwork(config) + } + try { wifiManager.saveConfiguration() } catch (_: Exception) {} + if (targetId < 0) { + notifyUnavailable("Android 7~9 无法刷新 QFT Wi-Fi 配置;请确认已授予位置权限并开启系统定位。") return } legacyTargetNetworkId = targetId + try { + Log.i(TAG, "attempt=$run legacy active scan requested=${wifiManager.startScan()}") + } catch (e: Exception) { + Log.w(TAG, "attempt=$run legacy active scan unavailable: ${e.message}") + } wifiManager.disconnect() if (!wifiManager.enableNetwork(targetId, true)) { notifyUnavailable("系统拒绝启用 QFT Wi-Fi 网络") @@ -284,6 +322,7 @@ class WifiConnector(context: Context) { } wifiManager.reconnect() val started = SystemClock.elapsedRealtime() + var associationRetried = false fun poll() { if (run != generation) return val info = wifiManager.connectionInfo @@ -297,8 +336,22 @@ class WifiConnector(context: Context) { return } } - if (SystemClock.elapsedRealtime() - started > 15_000) { - notifyUnavailable("连接 QFT Wi-Fi 超时。请确认发送设备的临时网络仍在运行。") + val elapsed = SystemClock.elapsedRealtime() - started + if (!associationRetried && elapsed > 8_000) { + associationRetried = true + notifyStatus("旧版 Android 首次关联未完成,正在刷新热点并重试…") + try { wifiManager.startScan() } catch (_: Exception) {} + try { + wifiManager.disconnect() + wifiManager.enableNetwork(targetId, true) + wifiManager.reconnect() + } catch (_: Exception) {} + } + if (elapsed > 30_000) { + notifyUnavailable( + "连接 QFT Wi-Fi 超时。已使用二维码中的最新密码重建网络;" + + "请确认发送手机仍停留在二维码页面,并检查旧手机的系统定位是否开启。" + ) } else { handler.postDelayed({ poll() }, 250) } @@ -540,18 +593,28 @@ class WifiConnector(context: Context) { callback = null currentNetwork = null listener = null - pendingSsid = null + pendingWifi = null pendingDelivered = null pendingTerminal = null handler.removeCallbacksAndMessages(null) - if (restoreLegacy && Build.VERSION.SDK_INT < 29) { + if (Build.VERSION.SDK_INT < 29) { + val target = legacyTargetNetworkId val previous = legacyPreviousNetworkId - if (previous != null && previous >= 0) { + if (restoreLegacy && previous != null && previous >= 0 && previous != target) { try { wifiManager.enableNetwork(previous, true) wifiManager.reconnect() } catch (_: Exception) {} } + // A QFT hotspot is session-scoped. Keeping its generated SSID/PSK + // in the legacy saved-network list is what made a later reservation + // with the same SSID silently reuse stale credentials. + if (target != null && target >= 0) { + try { + wifiManager.removeNetwork(target) + wifiManager.saveConfiguration() + } catch (_: Exception) {} + } } legacyPreviousNetworkId = null legacyTargetNetworkId = null diff --git a/docs/ANDROID_PHONE_TRANSFER.md b/docs/ANDROID_PHONE_TRANSFER.md index 84e838a..1bcd537 100644 --- a/docs/ANDROID_PHONE_TRANSFER.md +++ b/docs/ANDROID_PHONE_TRANSFER.md @@ -1,4 +1,4 @@ -# Android → Android 真机验收(v0.5.0-dev2) +# Android → Android 真机验收(v0.5.0-dev3) ## 构建约束 @@ -11,7 +11,7 @@ cd android ## 首轮验收 -1. 两台 Android 安装同一个 `v0.5.0-dev2` APK。 +1. 两台 Android 安装同一个 `v0.5.0-dev3` APK。 2. 发送手机进入“手机 → 手机”,选择至少两个文件并调整一次顺序。 3. 点击“创建发送二维码”,允许附近 Wi-Fi/位置权限。 4. 接收手机进入“扫码直传”,扫描发送手机二维码并确认系统连接提示。 @@ -22,7 +22,9 @@ cd android ## 必测网络组合 - Android 13+ → Android 13+:`NEARBY_WIFI_DEVICES` 权限与临时热点。 -- Android 8–12 → Android 10+:位置权限与 WPA2 临时热点。 +- Android 13+ 发送 → Android 7–9 接收:连续停止并重建两次发送热点;旧机每次均应使用二维码中的最新密码连接,不得复用同名热点旧凭据。 +- Android 13+ 发送 → Android 10–12 接收:新会话即使复用了热点名称,只要密码变化就必须创建新的系统配网请求。 +- 高版本发送端返回纯 WPA3、旧接收机不支持 SAE:应立即转入原局域网自动探测,不应停留在系统热点搜索。 - Android 7 发送端:两机先连接同一 Wi-Fi,验证自动 LAN 回落。 - 手动停止发送端热点:接收端应报连接中断,而不是无限等待。 - 传输中返回发送端首页:服务和临时热点应立即关闭。 diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 258548a..3bf38f3 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -99,7 +99,7 @@ The sender returns `206 Partial Content`, the matching `Content-Range`, and the For both direct-transfer directions, the Windows listener may accept connections non-blockingly for shutdown responsiveness, but each accepted file socket is switched to blocking I/O with explicit timeouts before reading or writing request bodies. This prevents `WSAEWOULDBLOCK (10035)` from turning an in-progress parallel transfer into an HTTP 500 failure. -## 6. Android → Android (`QFTPHONE2`, v0.5.0-dev2) +## 6. Android → Android (`QFTPHONE2`, v0.5.0-dev3) The sender starts an authenticated local HTTP service and encodes only session, port, sender identity and optional LocalOnlyHotspot credentials in the QR. The diff --git a/scripts/android_compat_selftest.py b/scripts/android_compat_selftest.py index 3a1d3a4..16b6474 100644 --- a/scripts/android_compat_selftest.py +++ b/scripts/android_compat_selftest.py @@ -19,6 +19,11 @@ assert 'MAX_WORKERS = 8' in upload and 'QFTDISC2:' in upload assert 'MAX_WORKERS = 8' in download and 'bytes=$start-$end' in download and 'completionMapFile' in download assert 'requestNetwork(request, cb)' in wifi and 'delivered.set(false)' in wifi assert 'wifiManager.startScan()' in wifi and '.setIsHiddenSsid(false)' in wifi +assert 'pendingWifi == wifi' in wifi and 'pendingSsid == wifi.ssid' not in wifi +assert 'wifiManager.updateNetwork(config)' in wifi and 'wifiManager.removeNetwork(target)' in wifi +assert 'elapsed > 30_000' in wifi and '旧版 Android 首次关联未完成' in wifi +assert 'canJoinAutomatically' in wifi and 'wifiManager.isWpa3SaeSupported' in wifi +assert 'unsupportedHotspot' in main and 'pair.copy(wifi = null)' in main assert 'probeConnectedNetwork' in upload and 'workers = 48' in upload assert 'awaitGatewayEndpoints' not in main assert 'QFTPHONE2:' in (ROOT/'android/app/src/main/java/com/qft/optical/PairingProtocol.kt').read_text()