fix: keep modern Android phone links on fast bands
This commit is contained in:
@@ -12,8 +12,8 @@ android {
|
||||
applicationId = "com.qft.optical"
|
||||
minSdk = 24
|
||||
targetSdk = 35
|
||||
versionCode = 27
|
||||
versionName = "0.5.0-dev4"
|
||||
versionCode = 28
|
||||
versionName = "0.5.0-dev5"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
@@ -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-dev4 · Android 7+ 到最新", 12f, MUTED))
|
||||
root.addView(text("QFT v0.5.0-dev5 · Android 7+ 到最新", 12f, MUTED))
|
||||
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
|
||||
}
|
||||
|
||||
@@ -958,6 +958,7 @@ class MainActivity : ComponentActivity() {
|
||||
else "正在校验 ${done + 1}/$total:$name"
|
||||
} },
|
||||
onPeer = { peer -> runOnUiThread {
|
||||
phoneHotspot.markPeerAuthenticated()
|
||||
phoneShareStatusText?.text = "$peer 已连接,正在接收队列文件…"
|
||||
} },
|
||||
)
|
||||
@@ -965,6 +966,9 @@ class MainActivity : ComponentActivity() {
|
||||
runOnUiThread {
|
||||
phoneHotspot.start(
|
||||
onStarted = { wifi -> showPhoneShareQr(server, wifi, null) },
|
||||
onStatus = { message ->
|
||||
if (phoneShareServer === server) phoneShareStatusText?.text = message
|
||||
},
|
||||
onFailed = { reason ->
|
||||
val endpoints = PhoneShareServer.localEndpoints(server.port)
|
||||
if (endpoints.isEmpty()) {
|
||||
@@ -1038,7 +1042,7 @@ class MainActivity : ComponentActivity() {
|
||||
root.addView(phoneShareStatusText)
|
||||
root.addView(text(
|
||||
if (wifi != null) {
|
||||
val link = if (wifi.ssid.startsWith("DIRECT-")) "兼容专用网络(2.4GHz / WPA2)" else "备用临时网络"
|
||||
val link = if (wifi.ssid.startsWith("DIRECT-")) "自适应专用网络(优先高速 / 自动兼容)" else "备用临时网络"
|
||||
"$link:${wifi.ssid}\n发送服务端口:${server.port}"
|
||||
}
|
||||
else "连接方式:两台手机当前同一 Wi-Fi\n发送服务端口:${server.port}",
|
||||
|
||||
@@ -15,152 +15,270 @@ import java.util.concurrent.atomic.AtomicBoolean
|
||||
/**
|
||||
* Owns the phone-share access point.
|
||||
*
|
||||
* A second LocalOnlyHotspot request cannot create a second SSID: Android shares
|
||||
* one underlying hotspot. QFT therefore prefers a Wi-Fi Direct group-owner AP,
|
||||
* which is WPA2 and accepts legacy Wi-Fi stations. Android 10+ senders force it
|
||||
* onto 2.4 GHz so Android 7-era receivers can see the same single network.
|
||||
* LocalOnlyHotspot remains a fallback for OEMs that disable P2P group creation.
|
||||
* Android only exposes one underlying local hotspot, so QFT uses one adaptive
|
||||
* Wi-Fi Direct group instead of pretending that two independent SSIDs can run
|
||||
* concurrently. Android 10+ starts on AUTO (normally 5 GHz when available). If
|
||||
* no authenticated peer appears, the exact same SSID/password is recreated on
|
||||
* 2.4 GHz so an old receiver's already-running Wi-Fi search can join without
|
||||
* rescanning the QR. LocalOnlyHotspot remains the final OEM fallback.
|
||||
*/
|
||||
class PhoneHotspotController(context: Context) {
|
||||
private companion object {
|
||||
const val LEGACY_BAND_FALLBACK_MS = 12_000L
|
||||
const val GROUP_READY_TIMEOUT_MS = 12_000L
|
||||
}
|
||||
|
||||
private val appContext = context.applicationContext
|
||||
private val wifiManager = appContext.getSystemService(WifiManager::class.java)
|
||||
private val p2pManager = appContext.getSystemService(Context.WIFI_P2P_SERVICE) as? WifiP2pManager
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var reservation: AutoCloseable? = null
|
||||
private var p2pChannel: WifiP2pManager.Channel? = null
|
||||
private var adaptiveFallback: Runnable? = null
|
||||
private var generation = 0
|
||||
@Volatile private var peerAuthenticated = false
|
||||
|
||||
fun start(
|
||||
onStarted: (WifiCredentials) -> Unit,
|
||||
onStatus: (String) -> Unit = {},
|
||||
onFailed: (String) -> Unit,
|
||||
) {
|
||||
close()
|
||||
val run = ++generation
|
||||
startCompatibilityGroup(
|
||||
run = run,
|
||||
onStarted = onStarted,
|
||||
onFallback = { reason ->
|
||||
if (run != generation) return@startCompatibilityGroup
|
||||
if (Build.VERSION.SDK_INT >= 26) {
|
||||
startLocalOnlyHotspot(run, onStarted) { localReason ->
|
||||
onFailed("$reason;$localReason")
|
||||
peerAuthenticated = false
|
||||
val finalFallbackStarted = AtomicBoolean(false)
|
||||
|
||||
fun fallBackToLocalOnly(reason: String) {
|
||||
if (run != generation || !finalFallbackStarted.compareAndSet(false, true)) return
|
||||
adaptiveFallback?.let(handler::removeCallbacks)
|
||||
adaptiveFallback = null
|
||||
removeP2pGroup {
|
||||
if (run == generation) {
|
||||
if (Build.VERSION.SDK_INT >= 26) {
|
||||
onStatus("$reason;正在启动系统备用热点…")
|
||||
startLocalOnlyHotspot(run, onStarted) { localReason ->
|
||||
onFailed("$reason;$localReason")
|
||||
}
|
||||
} else {
|
||||
onFailed("$reason;Android 7 无法创建备用临时热点,将使用当前局域网")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val manager = p2pManager ?: run {
|
||||
fallBackToLocalOnly("设备没有 Wi-Fi Direct 服务")
|
||||
return
|
||||
}
|
||||
val channel = try {
|
||||
manager.initialize(appContext, Looper.getMainLooper()) {
|
||||
fallBackToLocalOnly("Wi-Fi Direct 通道已断开")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fallBackToLocalOnly("初始化专用网络失败:${e.message ?: e.javaClass.simpleName}")
|
||||
return
|
||||
}
|
||||
p2pChannel = channel
|
||||
|
||||
if (Build.VERSION.SDK_INT >= 29) {
|
||||
val wifi = newSessionCredentials()
|
||||
onStatus("正在创建高速专用网络(自动选择 5GHz/2.4GHz)…")
|
||||
replaceConfiguredGroup(
|
||||
run = run,
|
||||
channel = channel,
|
||||
wifi = wifi,
|
||||
band = WifiP2pConfig.GROUP_OWNER_BAND_AUTO,
|
||||
onReady = {
|
||||
onStarted(wifi)
|
||||
onStatus("高速专用网络已就绪;12 秒未配对将自动切换旧机兼容频段")
|
||||
scheduleLegacyBandFallback(
|
||||
run = run,
|
||||
channel = channel,
|
||||
wifi = wifi,
|
||||
onStarted = onStarted,
|
||||
onStatus = onStatus,
|
||||
onFailed = ::fallBackToLocalOnly,
|
||||
)
|
||||
},
|
||||
onFailed = ::fallBackToLocalOnly,
|
||||
)
|
||||
} else {
|
||||
onStatus("正在创建系统兼容专用网络…")
|
||||
replaceLegacyGroup(
|
||||
run = run,
|
||||
channel = channel,
|
||||
onReady = { wifi ->
|
||||
onStarted(wifi)
|
||||
onStatus("WPA2 兼容专用网络已就绪")
|
||||
},
|
||||
onFailed = ::fallBackToLocalOnly,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Called after the HTTP session token has been authenticated. */
|
||||
fun markPeerAuthenticated() {
|
||||
peerAuthenticated = true
|
||||
adaptiveFallback?.let(handler::removeCallbacks)
|
||||
adaptiveFallback = null
|
||||
}
|
||||
|
||||
@RequiresApi(29)
|
||||
private fun scheduleLegacyBandFallback(
|
||||
run: Int,
|
||||
channel: WifiP2pManager.Channel,
|
||||
wifi: WifiCredentials,
|
||||
onStarted: (WifiCredentials) -> Unit,
|
||||
onStatus: (String) -> Unit,
|
||||
onFailed: (String) -> Unit,
|
||||
) {
|
||||
val task = Runnable {
|
||||
adaptiveFallback = null
|
||||
if (run != generation || peerAuthenticated) return@Runnable
|
||||
onStatus("尚未检测到接收端,正在用相同二维码切换到 2.4GHz 旧机兼容频段…")
|
||||
replaceConfiguredGroup(
|
||||
run = run,
|
||||
channel = channel,
|
||||
wifi = wifi,
|
||||
band = WifiP2pConfig.GROUP_OWNER_BAND_2GHZ,
|
||||
onReady = {
|
||||
onStarted(wifi) // Same credentials: QR contents do not change.
|
||||
onStatus("已切换 2.4GHz 兼容频段;旧版 Android 可继续自动搜索并连接")
|
||||
},
|
||||
onFailed = onFailed,
|
||||
)
|
||||
}
|
||||
adaptiveFallback = task
|
||||
handler.postDelayed(task, LEGACY_BAND_FALLBACK_MS)
|
||||
}
|
||||
|
||||
@RequiresApi(29)
|
||||
@Suppress("MissingPermission")
|
||||
private fun replaceConfiguredGroup(
|
||||
run: Int,
|
||||
channel: WifiP2pManager.Channel,
|
||||
wifi: WifiCredentials,
|
||||
band: Int,
|
||||
onReady: () -> Unit,
|
||||
onFailed: (String) -> Unit,
|
||||
) {
|
||||
replaceGroup(
|
||||
run = run,
|
||||
channel = channel,
|
||||
create = { listener ->
|
||||
val config = WifiP2pConfig.Builder()
|
||||
.setNetworkName(wifi.ssid)
|
||||
.setPassphrase(wifi.passphrase)
|
||||
.setGroupOperatingBand(band)
|
||||
.build()
|
||||
p2pManager?.createGroup(channel, config, listener)
|
||||
?: onFailed("Wi-Fi Direct 服务不可用")
|
||||
},
|
||||
onReady = { actual ->
|
||||
if (actual.ssid != wifi.ssid || actual.passphrase != wifi.passphrase) {
|
||||
onFailed("系统创建的专用网络凭据与会话不一致")
|
||||
} else {
|
||||
onFailed("$reason;Android 7 无法创建备用临时热点,将使用当前局域网")
|
||||
onReady()
|
||||
}
|
||||
},
|
||||
onFailed = onFailed,
|
||||
)
|
||||
}
|
||||
|
||||
@Suppress("MissingPermission")
|
||||
private fun startCompatibilityGroup(
|
||||
private fun replaceLegacyGroup(
|
||||
run: Int,
|
||||
onStarted: (WifiCredentials) -> Unit,
|
||||
onFallback: (String) -> Unit,
|
||||
channel: WifiP2pManager.Channel,
|
||||
onReady: (WifiCredentials) -> Unit,
|
||||
onFailed: (String) -> Unit,
|
||||
) {
|
||||
replaceGroup(
|
||||
run = run,
|
||||
channel = channel,
|
||||
create = { listener ->
|
||||
p2pManager?.createGroup(channel, listener)
|
||||
?: onFailed("Wi-Fi Direct 服务不可用")
|
||||
},
|
||||
onReady = onReady,
|
||||
onFailed = onFailed,
|
||||
)
|
||||
}
|
||||
|
||||
@Suppress("MissingPermission")
|
||||
private fun replaceGroup(
|
||||
run: Int,
|
||||
channel: WifiP2pManager.Channel,
|
||||
create: (WifiP2pManager.ActionListener) -> Unit,
|
||||
onReady: (WifiCredentials) -> Unit,
|
||||
onFailed: (String) -> Unit,
|
||||
) {
|
||||
val manager = p2pManager ?: run {
|
||||
onFallback("设备没有 Wi-Fi Direct 服务")
|
||||
return
|
||||
}
|
||||
val terminal = AtomicBoolean(false)
|
||||
var localChannel: WifiP2pManager.Channel? = null
|
||||
|
||||
fun fallback(reason: String) {
|
||||
if (run != generation || !terminal.compareAndSet(false, true)) return
|
||||
val channel = localChannel
|
||||
if (p2pChannel === channel) p2pChannel = null
|
||||
if (channel != null) {
|
||||
fun fail(reason: String) {
|
||||
if (run == generation && terminal.compareAndSet(false, true)) onFailed(reason)
|
||||
}
|
||||
|
||||
fun waitForGroup() {
|
||||
val deadline = SystemClock.elapsedRealtime() + GROUP_READY_TIMEOUT_MS
|
||||
fun poll() {
|
||||
if (run != generation || terminal.get()) return
|
||||
try {
|
||||
manager.removeGroup(channel, object : WifiP2pManager.ActionListener {
|
||||
override fun onSuccess() = onFallback(reason)
|
||||
override fun onFailure(removeReason: Int) = onFallback(reason)
|
||||
})
|
||||
} catch (_: Exception) {
|
||||
onFallback(reason)
|
||||
}
|
||||
} else {
|
||||
onFallback(reason)
|
||||
}
|
||||
}
|
||||
|
||||
val channel = try {
|
||||
manager.initialize(appContext, Looper.getMainLooper()) {
|
||||
fallback("Wi-Fi Direct 通道已断开")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
onFallback("初始化兼容专用网络失败:${e.message ?: e.javaClass.simpleName}")
|
||||
return
|
||||
}
|
||||
localChannel = channel
|
||||
p2pChannel = channel
|
||||
|
||||
val createListener = object : WifiP2pManager.ActionListener {
|
||||
override fun onSuccess() {
|
||||
val deadline = SystemClock.elapsedRealtime() + 12_000L
|
||||
fun pollGroup() {
|
||||
if (run != generation || terminal.get()) return
|
||||
try {
|
||||
manager.requestGroupInfo(channel) { group ->
|
||||
if (run != generation || terminal.get()) return@requestGroupInfo
|
||||
val ssid = group?.networkName.orEmpty()
|
||||
val passphrase = group?.passphrase.orEmpty()
|
||||
if (group?.isGroupOwner == true && ssid.isNotBlank() && passphrase.length in 8..63) {
|
||||
if (!terminal.compareAndSet(false, true)) return@requestGroupInfo
|
||||
onStarted(WifiCredentials(ssid, passphrase, "WPA2"))
|
||||
} else if (SystemClock.elapsedRealtime() >= deadline) {
|
||||
fallback("创建 2.4GHz/WPA2 兼容专用网络超时")
|
||||
} else {
|
||||
handler.postDelayed({ pollGroup() }, 180L)
|
||||
p2pManager?.requestGroupInfo(channel) { group ->
|
||||
if (run != generation || terminal.get()) return@requestGroupInfo
|
||||
val ssid = group?.networkName.orEmpty()
|
||||
val passphrase = group?.passphrase.orEmpty()
|
||||
if (group?.isGroupOwner == true && ssid.isNotBlank() && passphrase.length in 8..63) {
|
||||
if (terminal.compareAndSet(false, true)) {
|
||||
onReady(WifiCredentials(ssid, passphrase, "WPA2"))
|
||||
}
|
||||
} else if (SystemClock.elapsedRealtime() >= deadline) {
|
||||
fail("创建专用网络超时")
|
||||
} else {
|
||||
handler.postDelayed({ poll() }, 180L)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fallback("读取兼容专用网络信息失败:${e.message ?: e.javaClass.simpleName}")
|
||||
}
|
||||
} ?: fail("Wi-Fi Direct 服务不可用")
|
||||
} catch (e: Exception) {
|
||||
fail("读取专用网络信息失败:${e.message ?: e.javaClass.simpleName}")
|
||||
}
|
||||
pollGroup()
|
||||
}
|
||||
poll()
|
||||
}
|
||||
|
||||
override fun onFailure(reason: Int) {
|
||||
fallback("系统拒绝创建 2.4GHz/WPA2 兼容专用网络(错误 $reason)")
|
||||
val listener = object : WifiP2pManager.ActionListener {
|
||||
override fun onSuccess() = waitForGroup()
|
||||
override fun onFailure(reason: Int) = fail("系统拒绝创建专用网络(错误 $reason)")
|
||||
}
|
||||
val startCreate = {
|
||||
if (run == generation && !terminal.get()) {
|
||||
try {
|
||||
create(listener)
|
||||
} catch (e: Exception) {
|
||||
fail("启动专用网络失败:${e.message ?: e.javaClass.simpleName}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun createGroup() {
|
||||
if (run != generation || terminal.get()) return
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= 29) {
|
||||
manager.createGroup(channel, compatibilityConfig(), createListener)
|
||||
} else {
|
||||
// API 24–28 creates the interoperable legacy-client group
|
||||
// with system-generated DIRECT-* credentials.
|
||||
manager.createGroup(channel, createListener)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fallback("启动兼容专用网络失败:${e.message ?: e.javaClass.simpleName}")
|
||||
}
|
||||
}
|
||||
|
||||
// A stale persistent P2P group can keep old credentials or a 5 GHz
|
||||
// channel. Remove it before creating this session's 2.4 GHz group.
|
||||
// Remove stale/present group before both initial creation and adaptive
|
||||
// band switching. Credentials supplied to `create` stay unchanged.
|
||||
try {
|
||||
manager.removeGroup(channel, object : WifiP2pManager.ActionListener {
|
||||
override fun onSuccess() = createGroup()
|
||||
override fun onFailure(reason: Int) = createGroup()
|
||||
})
|
||||
p2pManager?.removeGroup(channel, object : WifiP2pManager.ActionListener {
|
||||
override fun onSuccess() = startCreate()
|
||||
override fun onFailure(reason: Int) = startCreate()
|
||||
}) ?: fail("Wi-Fi Direct 服务不可用")
|
||||
} catch (_: Exception) {
|
||||
createGroup()
|
||||
startCreate()
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresApi(29)
|
||||
private fun compatibilityConfig(): WifiP2pConfig {
|
||||
private fun newSessionCredentials(): WifiCredentials {
|
||||
val random = ByteArray(12).also { SecureRandom().nextBytes(it) }
|
||||
val token = random.joinToString("") { "%02x".format(it.toInt() and 0xff) }
|
||||
return WifiP2pConfig.Builder()
|
||||
.setNetworkName("DIRECT-QF-QFT${token.take(6)}")
|
||||
.setPassphrase(token.take(16))
|
||||
.setGroupOperatingBand(WifiP2pConfig.GROUP_OWNER_BAND_2GHZ)
|
||||
.build()
|
||||
return WifiCredentials(
|
||||
ssid = "DIRECT-QF-QFT${token.take(6)}",
|
||||
passphrase = token.take(16),
|
||||
security = "WPA2",
|
||||
)
|
||||
}
|
||||
|
||||
@RequiresApi(26)
|
||||
@@ -218,10 +336,34 @@ class PhoneHotspotController(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("MissingPermission")
|
||||
private fun removeP2pGroup(done: () -> Unit) {
|
||||
val channel = p2pChannel
|
||||
p2pChannel = null
|
||||
if (channel == null) {
|
||||
done()
|
||||
return
|
||||
}
|
||||
val once = AtomicBoolean(false)
|
||||
fun finish() {
|
||||
if (once.compareAndSet(false, true)) done()
|
||||
}
|
||||
try {
|
||||
p2pManager?.removeGroup(channel, object : WifiP2pManager.ActionListener {
|
||||
override fun onSuccess() = finish()
|
||||
override fun onFailure(reason: Int) = finish()
|
||||
}) ?: finish()
|
||||
} catch (_: Exception) {
|
||||
finish()
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("MissingPermission")
|
||||
fun close() {
|
||||
generation++
|
||||
handler.removeCallbacksAndMessages(null)
|
||||
adaptiveFallback = null
|
||||
peerAuthenticated = false
|
||||
try { reservation?.close() } catch (_: Exception) {}
|
||||
reservation = null
|
||||
val channel = p2pChannel
|
||||
|
||||
Reference in New Issue
Block a user