fix direct connection startup and drag stability

This commit is contained in:
zhy200308
2026-08-12 14:28:49 +08:00
parent 8b3f5c0216
commit 1c5e015285
9 changed files with 164 additions and 59 deletions
+2 -2
View File
@@ -12,8 +12,8 @@ android {
applicationId = "com.qft.optical"
minSdk = 24
targetSdk = 35
versionCode = 22
versionName = "0.4.10"
versionCode = 23
versionName = "0.4.11"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
@@ -202,7 +202,7 @@ class MainActivity : ComponentActivity() {
) { showReceivedFiles() })
root.addView(space(22))
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED))
root.addView(text("QFT v0.4.10 · Android 7+ 到最新", 12f, MUTED))
root.addView(text("QFT v0.4.11 · Android 7+ 到最新", 12f, MUTED))
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
}
@@ -636,15 +636,15 @@ class MainActivity : ComponentActivity() {
transferExecutor.execute {
if (attempt != pairConnectionAttempt) return@execute
val dedicatedWifi = pair.wifi != null
val gateways = if (dedicatedWifi) {
runOnUiThread { updateConnectingStatus("专用 Wi-Fi 已连接 · 正在读取实际网关…") }
wifiConnector.awaitGatewayEndpoints(network, pair.port, timeoutMs = 3_500L)
} else {
wifiConnector.gatewayEndpoints(network, pair.port)
}
val gateways = wifiConnector.gatewayEndpoints(network, pair.port)
val routedEndpoints = if (dedicatedWifi) emptyList() else {
wifiConnector.endpointsOnNetwork(network, pair.endpoints, pair.port)
}
var subnet = if (dedicatedWifi) {
wifiConnector.subnetEndpoints(network, pair.port)
} else {
emptyList()
}
val directCandidates = EndpointRouting.afterConnection(
dedicatedWifi = dedicatedWifi,
gatewayEndpoints = gateways,
@@ -655,22 +655,30 @@ class MainActivity : ComponentActivity() {
// 不使用二维码地址,也不猜测 192.168.137/49 网段。
runOnUiThread {
updateConnectingStatus(
if (dedicatedWifi) "已取得专用网络网关 · 正在认证电脑…"
if (dedicatedWifi) "专用 Wi-Fi 已连接 · 正在并行认证网关和电脑…"
else "网络已就绪 · 正在连接同网段电脑…"
)
}
val direct = UploadClient.probeEndpoints(
network = network,
pairing = pair,
deviceName = receiverDeviceLabel,
endpoints = directCandidates,
connectMs = if (dedicatedWifi) 650 else 400,
readMs = if (dedicatedWifi) 850 else 600,
)
val direct = if (dedicatedWifi) {
UploadClient.probeConnectedNetwork(
network = network,
pairing = pair,
deviceName = receiverDeviceLabel,
endpoints = directCandidates + subnet,
)
} else {
UploadClient.probeEndpoints(
network = network,
pairing = pair,
deviceName = receiverDeviceLabel,
endpoints = directCandidates,
connectMs = 400,
readMs = 600,
)
}
// 直连不通才退回发现流程:UDP 广播 → 子网扫描
// 网关/子网并行快探不通才退回 UDP,并刷新路由后再恢复。
var discovered: String? = null
var subnet: List<String> = emptyList()
if (direct == null) {
runOnUiThread {
updateConnectingStatus(
@@ -684,7 +692,11 @@ class MainActivity : ComponentActivity() {
hosts = wifiConnector.discoveryHosts(network),
deviceName = receiverDeviceLabel,
)
subnet = wifiConnector.subnetEndpoints(network, pair.port)
// LinkProperties may have gained routes while the first
// scan was running; refresh the actual connected subnet.
if (dedicatedWifi) {
subnet = wifiConnector.subnetEndpoints(network, pair.port)
}
runOnUiThread {
updateConnectingStatus(
if (discovered != null) "已通过 UDP 找到电脑 · 正在验证接收服务…"
@@ -1096,38 +1108,48 @@ class MainActivity : ComponentActivity() {
file: SelectedFile,
container: LinearLayout,
) {
var downRawY = 0f
var startIndex = -1
handle.setOnTouchListener { view, event ->
if (uploadRunning) return@setOnTouchListener false
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
view.parent?.requestDisallowInterceptTouchEvent(true)
downRawY = event.rawY
startIndex = selectedFiles.indexOfFirst { it.uri == file.uri }
row.alpha = 0.72f
row.translationZ = dp(8).toFloat()
true
}
MotionEvent.ACTION_MOVE -> {
val location = IntArray(2)
container.getLocationOnScreen(location)
val y = event.rawY - location[1]
var target = container.childCount - 1
for (index in 0 until container.childCount) {
val child = container.getChildAt(index)
if (y < child.top + child.height / 2f) {
target = index
break
}
}
val current = selectedFiles.indexOfFirst { it.uri == file.uri }
if (moveQueueItem(selectedFiles, current, target)) {
container.removeView(row)
container.addView(row, target)
}
// Never remove/reinsert the touched View here. Several OEM
// frameworks crash when a Button is detached while its
// dispatchTouchEvent is still on the stack. Move only the
// visual row; commit the list order once on ACTION_UP.
row.translationY = event.rawY - downRawY
true
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
view.parent?.requestDisallowInterceptTouchEvent(false)
row.alpha = 1f
view.performClick()
renderSelectedFiles()
row.translationZ = 0f
val averageHeight = (0 until container.childCount)
.map { container.getChildAt(it).height.coerceAtLeast(1) }
.average()
.takeIf { it.isFinite() && it > 0.0 }
?: row.height.coerceAtLeast(1).toDouble()
val deltaRows = kotlin.math.round(row.translationY.toDouble() / averageHeight).toInt()
row.translationY = 0f
if (
event.actionMasked == MotionEvent.ACTION_UP &&
startIndex >= 0 &&
selectedFiles.isNotEmpty()
) {
val target = (startIndex + deltaRows).coerceIn(0, selectedFiles.lastIndex)
moveQueueItem(selectedFiles, startIndex, target)
view.performClick()
}
container.post { renderSelectedFiles() }
true
}
else -> false
@@ -163,11 +163,34 @@ object UploadClient {
.filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) }
.distinct()
val scan = subnetEndpoints
.map { it.trim().removeSuffix("/") }
.filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) }
.filterNot { it in fast }
.distinct()
if (dedicatedWifi) {
// The group-owner route may remain absent on some Huawei/Windows
// combinations even though DHCP already supplied a usable /24.
// Probe gateway and the real connected subnet together, repeating
// while Windows finishes accepting the Wi-Fi Direct peer.
val candidates = (fast + scan).distinct()
val deadline = android.os.SystemClock.elapsedRealtime() + 6_000L
while (candidates.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < deadline) {
probeCandidatesParallel(
network, pairing, deviceName, candidates,
workers = 48, connectMs = 180, readMs = 220,
)?.let { return it }
try { Thread.sleep(80) } catch (_: InterruptedException) { return null }
}
return null
}
// Give a newly associated Direct network enough time for ARP, the group
// owner route and Windows' new-network firewall profile to settle. A
// successful candidate still returns immediately, so this extends only
// the failure/recovery path.
val fastWindowMs = if (dedicatedWifi) 4_000L else 1_050L
val fastWindowMs = 1_050L
val fastDeadline = android.os.SystemClock.elapsedRealtime() + fastWindowMs
while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < fastDeadline) {
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 12, connectMs = 220, readMs = 260)
@@ -178,11 +201,6 @@ object UploadClient {
// Stage 2: actual connected subnet fallback. This specifically fixes the
// case where Windows Wi-Fi Direct is up but uses an unexpected gateway
// address. Up to /24 is scanned concurrently and still session-authenticated.
val scan = subnetEndpoints
.map { it.trim().removeSuffix("/") }
.filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) }
.filterNot { it in fast }
.distinct()
if (scan.isNotEmpty()) {
probeCandidatesParallel(network, pairing, deviceName, scan, workers = 48, connectMs = 180, readMs = 220)
?.let { return it }
@@ -190,7 +208,7 @@ object UploadClient {
// One final pass covers a route/firewall transition that completed while
// the actual connected subnet fallback was running.
val deadline = android.os.SystemClock.elapsedRealtime() + if (dedicatedWifi) 1_200L else 500L
val deadline = android.os.SystemClock.elapsedRealtime() + 500L
while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < deadline) {
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 12, connectMs = 240, readMs = 260)
?.let { return it }
@@ -223,6 +241,26 @@ object UploadClient {
readMs = readMs,
)
/**
* Dedicated Wi-Fi fast path. The Windows group owner is normally the first
* host in the actual connected subnet, so scan it immediately instead of
* waiting several seconds for Android to publish a default gateway route.
*/
fun probeConnectedNetwork(
network: Network?,
pairing: PairingPayload,
deviceName: String,
endpoints: List<String>,
): String? = probeCandidatesParallel(
network = network,
pairing = pairing,
deviceName = deviceName,
candidates = endpoints.distinct(),
workers = 48,
connectMs = 180,
readMs = 220,
)
private fun probeCandidatesParallel(
network: Network?,
pairing: PairingPayload,
@@ -113,11 +113,22 @@ class WifiConnector(context: Context) {
@Suppress("MissingPermission")
private fun connectModern(run: Int, wifi: WifiCredentials) {
Log.i(TAG, "attempt=$run request SSID=${wifi.ssid}")
notifyStatus("正在等待 Android 系统连接确认;确认后本页将继续显示进度")
// Ask the radio for a fresh scan immediately before presenting the
// NetworkSpecifier chooser. Some OEMs otherwise reuse an old scan cache
// and keep showing “searching” even though Windows has just started the
// QFT SSID. Android may throttle this call; requestNetwork still runs.
try {
val scanStarted = wifiManager.startScan()
Log.i(TAG, "attempt=$run active scan requested=$scanStarted")
} catch (e: Exception) {
Log.w(TAG, "attempt=$run active scan unavailable: ${e.message}")
}
notifyStatus("正在刷新 Wi-Fi 列表并连接 ${wifi.ssid}…")
val specifier = try {
WifiNetworkSpecifier.Builder()
.setSsid(wifi.ssid)
.setWpa2Passphrase(wifi.passphrase)
.setIsHiddenSsid(false)
.build()
} catch (e: Exception) {
notifyUnavailable("配网参数无效:${e.message}")
@@ -224,7 +235,7 @@ class WifiConnector(context: Context) {
handler.postDelayed({
if (pending()) listener?.onStatus?.invoke("仍在等待系统完成配网…")
}, 8_000)
}, 4_000)
handler.postDelayed({
if (pending()) listener?.onStatus?.invoke(
"系统仍在搜索 $ssid。若弹窗里一直没出现这个名字," +