fix: connect older Android receivers to phone hotspots

This commit is contained in:
zhy200308
2026-08-12 16:27:02 +08:00
parent 04a2d7fb10
commit 2ff0741fff
7 changed files with 139 additions and 48 deletions
@@ -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 {
@@ -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