fix: connection survives mic permission dialog, add reconnect reuse

- Permission dialog triggers onStop/onStart; previously each foreground() created new WS,
  causing busy-lock conflict and disconnect
- Now: onStop stops audio but keeps connection alive for 30s; onStart reuses if still open
- DebugLogUpload: runtime policy check, screen shows upload result (HTTP status / failure reason)
- Reduced audio frame log volume to avoid flooding upload queue

Version 0.2.6-m5-fix7
This commit is contained in:
zenord
2026-10-11 18:19:04 +08:00
parent 198fe51cec
commit c3e5481d19
4 changed files with 112 additions and 19 deletions
@@ -3,6 +3,7 @@ package com.gorios.lanvoice
import android.Manifest import android.Manifest
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.os.Bundle import android.os.Bundle
import android.security.NetworkSecurityPolicy
import androidx.activity.ComponentActivity import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts
@@ -21,6 +22,7 @@ import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
@@ -39,6 +41,7 @@ import com.gorios.lanvoice.expression.ExpressionController
import com.gorios.lanvoice.expression.ExpressionControls import com.gorios.lanvoice.expression.ExpressionControls
import com.gorios.lanvoice.expression.ExpressionStatus import com.gorios.lanvoice.expression.ExpressionStatus
import com.gorios.lanvoice.expression.ExpressionUiState import com.gorios.lanvoice.expression.ExpressionUiState
import kotlinx.coroutines.delay
class MainActivity : ComponentActivity() { class MainActivity : ComponentActivity() {
private var state by mutableStateOf(VoiceUiState()) private var state by mutableStateOf(VoiceUiState())
@@ -56,18 +59,23 @@ class MainActivity : ComponentActivity() {
else if (!granted) expressions.permissionDenied() else if (!granted) expressions.permissionDenied()
} }
private val microphonePermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> private val microphonePermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
val shouldStart = pendingStart DebugLogUpload.log("audio", "microphone permission granted=$granted foreground=$inForeground")
if (granted) startPendingVoice()
else {
pendingStart = false pendingStart = false
if (granted && shouldStart) session.startVoice() session.permissionDenied()
else if (!granted) session.permissionDenied() }
} }
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
DebugLogUpload.appLaunch(packageManager.getPackageInfo(packageName, 0).versionName ?: "unknown") DebugLogUpload.appLaunch(
packageManager.getPackageInfo(packageName, 0).versionName ?: "unknown",
NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted("192.168.31.61"),
)
session = VoiceSession( session = VoiceSession(
getString(R.string.voice_server_host), resources.getInteger(R.integer.voice_server_port), getString(R.string.voice_server_host), resources.getInteger(R.integer.voice_server_port),
onState = { state = it }, onState = { state = it; startPendingVoice() },
onConnectionLog = { connectionLogs = (connectionLogs + it).takeLast(3) }, onConnectionLog = { connectionLogs = (connectionLogs + it).takeLast(3) },
) )
expressions = ExpressionController(this, this) { expressionState = it } expressions = ExpressionController(this, this) { expressionState = it }
@@ -88,6 +96,7 @@ class MainActivity : ComponentActivity() {
} }
private fun toggleVoice() { private fun toggleVoice() {
DebugLogUpload.log("audio", "voice button active=${state.voiceActive}")
if (state.voiceActive) { if (state.voiceActive) {
pendingStart = false pendingStart = false
session.stopVoice() session.stopVoice()
@@ -95,28 +104,42 @@ class MainActivity : ComponentActivity() {
session.startVoice() session.startVoice()
} else if (!pendingStart) { } else if (!pendingStart) {
pendingStart = true pendingStart = true
DebugLogUpload.log("audio", "microphone permission requested")
microphonePermission.launch(Manifest.permission.RECORD_AUDIO) microphonePermission.launch(Manifest.permission.RECORD_AUDIO)
} }
} }
private fun startPendingVoice() {
if (pendingStart && inForeground && state.connection == ConnectionStatus.CONNECTED &&
checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
pendingStart = false
session.startVoice()
}
}
override fun onStart() { override fun onStart() {
super.onStart() super.onStart()
inForeground = true inForeground = true
DebugLogUpload.log("connect", "activity onStart")
connectionLogs = emptyList() connectionLogs = emptyList()
session.foreground() session.foreground()
startPendingVoice()
} }
override fun onStop() { override fun onStop() {
inForeground = false inForeground = false
val permissionInFlight = pendingStart || pendingCamera
DebugLogUpload.log("connect", "activity onStop permission=$permissionInFlight changingConfig=$isChangingConfigurations")
pendingCamera = false pendingCamera = false
expressions.stop() expressions.stop()
pendingStart = false if (!permissionInFlight) pendingStart = false
session.background() session.background(keepConnectionForPermission = permissionInFlight)
super.onStop() super.onStop()
} }
override fun onDestroy() { override fun onDestroy() {
expressions.release() expressions.release()
DebugLogUpload.log("connect", "activity onDestroy changingConfig=$isChangingConfigurations")
session.release() session.release()
super.onDestroy() super.onDestroy()
} }
@@ -131,6 +154,12 @@ fun Home(
val gold = Color(0xFFE8C884) val gold = Color(0xFFE8C884)
val muted = Color(0xFF9CA3AF) val muted = Color(0xFF9CA3AF)
val connected = state.connection == ConnectionStatus.CONNECTED val connected = state.connection == ConnectionStatus.CONNECTED
val uploadResult by produceState(initialValue = DebugLogUpload.lastResult) {
while (true) {
value = DebugLogUpload.lastResult
delay(1_000L)
}
}
Box(Modifier.fillMaxSize().background(Color(0xFF121220)).padding(24.dp)) { Box(Modifier.fillMaxSize().background(Color(0xFF121220)).padding(24.dp)) {
Column( Column(
modifier = Modifier.align(Alignment.TopCenter).padding(top = 24.dp), modifier = Modifier.align(Alignment.TopCenter).padding(top = 24.dp),
@@ -154,7 +183,7 @@ fun Home(
modifier = Modifier.background(Color(0xFF242433), RoundedCornerShape(50)) modifier = Modifier.background(Color(0xFF242433), RoundedCornerShape(50))
.padding(horizontal = 20.dp, vertical = 10.dp) .padding(horizontal = 20.dp, vertical = 10.dp)
) )
Text("调试日志已开启", color = muted, fontSize = 12.sp, modifier = Modifier.padding(top = 4.dp)) Text("调试日志已开启 · $uploadResult", color = muted, fontSize = 12.sp, modifier = Modifier.padding(top = 4.dp))
if (connectionLogs.isNotEmpty()) { if (connectionLogs.isNotEmpty()) {
Text( Text(
text = connectionLogs.takeLast(3).joinToString("\n"), text = connectionLogs.takeLast(3).joinToString("\n"),
@@ -29,6 +29,7 @@ class VoiceSession(
private var state = VoiceUiState() private var state = VoiceUiState()
private var foreground = false private var foreground = false
private var released = false private var released = false
private var backgroundTimeout: Runnable? = null
private var captureEpoch = 0L private var captureEpoch = 0L
private var capturing = false private var capturing = false
private var currentTurn = 0L private var currentTurn = 0L
@@ -66,16 +67,34 @@ class VoiceSession(
fun foreground() { fun foreground() {
checkMainThread() checkMainThread()
if (released) return if (released) return
backgroundTimeout?.let { main.removeCallbacks(it) }
backgroundTimeout = null
if (foreground) {
DebugLogUpload.log("connect", "foreground skipped: already foreground")
return
}
DebugLogUpload.log("connect", "session foreground")
foreground = true foreground = true
update(state.copy(aec = capture.aecAvailability())) update(state.copy(aec = capture.aecAvailability()))
dialogue.connect() if (!dialogue.hasActiveConnection()) dialogue.connect()
else DebugLogUpload.log("connect", "foreground reused active connection")
} }
fun background() { fun background(keepConnectionForPermission: Boolean = false) {
checkMainThread() checkMainThread()
foreground = false foreground = false
stopVoice(sendControls = false) stopVoice(sendControls = false)
dialogue.disconnect() backgroundTimeout?.let { main.removeCallbacks(it) }
backgroundTimeout = null
DebugLogUpload.log("connect", "session background permission=$keepConnectionForPermission")
if (keepConnectionForPermission && !released) {
// A permission Activity can stop this Activity on some ROMs. Stop audio,
// but reuse the authorized WS when it returns. Bound retention if the user leaves.
backgroundTimeout = Runnable {
backgroundTimeout = null
if (!foreground && !released) dialogue.disconnect()
}.also { main.postDelayed(it, 30_000L) }
} else dialogue.disconnect()
} }
fun release() { fun release() {
@@ -90,6 +109,7 @@ class VoiceSession(
/** Activity verifies runtime permission first; capture still handles permission revocation. */ /** Activity verifies runtime permission first; capture still handles permission revocation. */
fun startVoice() { fun startVoice() {
checkMainThread() checkMainThread()
DebugLogUpload.log("audio", "start_voice state=${state.connection.name.lowercase()} foreground=$foreground active=${state.voiceActive}")
if (released || !foreground || state.connection != ConnectionStatus.CONNECTED || state.voiceActive) return if (released || !foreground || state.connection != ConnectionStatus.CONNECTED || state.voiceActive) return
if (!dialogue.listen(true)) return if (!dialogue.listen(true)) return
update(state.copy(voiceActive = true, phase = VoicePhase.LISTENING, guidance = null)) update(state.copy(voiceActive = true, phase = VoicePhase.LISTENING, guidance = null))
@@ -142,6 +162,7 @@ class VoiceSession(
if (!isActive() || capturing) return if (!isActive() || capturing) return
capturing = true capturing = true
val epoch = ++captureEpoch val epoch = ++captureEpoch
DebugLogUpload.log("audio", "capture start")
capture.start( capture.start(
onFrame = { pcm -> onFrame = { pcm ->
main.post { main.post {
@@ -12,6 +12,10 @@ import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response import okhttp3.Response
import org.json.JSONObject import org.json.JSONObject
import java.io.IOException import java.io.IOException
import java.net.ConnectException
import java.net.Proxy
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicInteger
@@ -23,12 +27,15 @@ object DebugLogUpload {
private val tags = setOf("connect", "ws", "auth", "audio", "error") private val tags = setOf("connect", "ws", "auth", "audio", "error")
private val pending = AtomicInteger() private val pending = AtomicInteger()
private val launchSent = AtomicBoolean() private val launchSent = AtomicBoolean()
@Volatile var lastResult: String = "等待发送"
private set
private val json = "application/json; charset=utf-8".toMediaType() private val json = "application/json; charset=utf-8".toMediaType()
// Build independently, never newBuilder() from the voice client. HTTP-only avoids // Build independently, never newBuilder() from the voice client. HTTP-only avoids
// initializing TLS for the diagnostic channel whose purpose includes TLS failures. // initializing TLS for the diagnostic channel whose purpose includes TLS failures.
private val client by lazy { private val client by lazy {
OkHttpClient.Builder() OkHttpClient.Builder()
.connectionSpecs(listOf(ConnectionSpec.CLEARTEXT)) .connectionSpecs(listOf(ConnectionSpec.CLEARTEXT))
.proxy(Proxy.NO_PROXY) // Direct LAN request, independent of any system HTTP proxy.
.connectionPool(ConnectionPool(2, 30, TimeUnit.SECONDS)) .connectionPool(ConnectionPool(2, 30, TimeUnit.SECONDS))
.dispatcher(Dispatcher().apply { maxRequests = 2; maxRequestsPerHost = 2 }) .dispatcher(Dispatcher().apply { maxRequests = 2; maxRequestsPerHost = 2 })
.connectTimeout(3, TimeUnit.SECONDS) .connectTimeout(3, TimeUnit.SECONDS)
@@ -41,8 +48,11 @@ object DebugLogUpload {
.build() .build()
} }
fun appLaunch(version: String) { fun appLaunch(version: String, cleartextPermitted: Boolean = true) {
if (launchSent.compareAndSet(false, true)) log("connect", "app_launch version=$version") if (!cleartextPermitted) lastResult = "系统禁止网关明文 HTTP"
if (launchSent.compareAndSet(false, true)) {
log("connect", "app_launch version=$version cleartext=$cleartextPermitted")
}
} }
fun log(tag: String, message: String) { fun log(tag: String, message: String) {
@@ -61,16 +71,28 @@ object DebugLogUpload {
.toString().toRequestBody(json) .toString().toRequestBody(json)
client.newCall(Request.Builder().url(ENDPOINT).post(body).build()).enqueue(object : Callback { client.newCall(Request.Builder().url(ENDPOINT).post(body).build()).enqueue(object : Callback {
override fun onFailure(call: Call, error: IOException) { override fun onFailure(call: Call, error: IOException) {
lastResult = "上传失败:${failureSummary(error)}"
pending.decrementAndGet() // No retries, recursive logs or UI updates. pending.decrementAndGet() // No retries, recursive logs or UI updates.
} }
override fun onResponse(call: Call, response: Response) { override fun onResponse(call: Call, response: Response) {
lastResult = "HTTP ${response.code}"
try { response.close() } catch (_: Exception) { } try { response.close() } catch (_: Exception) { }
finally { pending.decrementAndGet() } finally { pending.decrementAndGet() }
} }
}) })
} catch (_: Exception) { } catch (error: Exception) {
lastResult = "上传失败:${failureSummary(error)}"
pending.decrementAndGet() // Setup/enqueue errors must also be silent. pending.decrementAndGet() // Setup/enqueue errors must also be silent.
} }
} }
private fun failureSummary(error: Exception): String = when {
error.message?.contains("CLEARTEXT", ignoreCase = true) == true -> "明文 HTTP 被系统禁止"
error is SocketTimeoutException || error.message == "timeout" -> "超时"
error is ConnectException -> "TCP 连接失败"
error is UnknownHostException -> "地址解析失败"
error is SecurityException -> "网络权限被拒绝"
else -> error.javaClass.simpleName
}
} }
@@ -72,11 +72,16 @@ class DialogueClient(
private var wsOpened = false private var wsOpened = false
private var authReceived = false private var authReceived = false
private var helloSent = false private var helloSent = false
private var loggedAudioTurn: Long? = null
private var handshakeTimeout: Runnable? = null private var handshakeTimeout: Runnable? = null
fun connect() { fun connect() {
checkMainThread() checkMainThread()
check(!released) { "DialogueClient has been released" } check(!released) { "DialogueClient has been released" }
if (hasActiveConnection()) {
connectionLog("connect skipped: session active", "connect")
return
}
generation++ generation++
connectionLog("connect_start #$generation", "connect") connectionLog("connect_start #$generation", "connect")
cancelHandshakeTimeout() cancelHandshakeTimeout()
@@ -84,6 +89,7 @@ class DialogueClient(
wsOpened = false wsOpened = false
authReceived = false authReceived = false
helloSent = false helloSent = false
loggedAudioTurn = null
healthCall?.cancel() healthCall?.cancel()
healthCall = null healthCall = null
socket?.cancel() socket?.cancel()
@@ -107,6 +113,11 @@ class DialogueClient(
startHealthProbe(attempt) startHealthProbe(attempt)
} }
fun hasActiveConnection(): Boolean {
checkMainThread()
return !released && (socket != null || healthCall != null)
}
private fun startHealthProbe(attempt: Long) { private fun startHealthProbe(attempt: Long) {
healthPhase = "health request" healthPhase = "health request"
try { try {
@@ -192,7 +203,11 @@ class DialogueClient(
client.connectionPool.evictAll() client.connectionPool.evictAll()
} }
fun listen(start: Boolean): Boolean = send(DialogueProtocol.listen(start)) fun listen(start: Boolean): Boolean {
checkMainThread()
connectionLog(if (start) "listen start requested" else "listen stop requested", "audio")
return send(DialogueProtocol.listen(start))
}
fun abort(turnId: Long): Boolean = send(DialogueProtocol.abort(turnId)) fun abort(turnId: Long): Boolean = send(DialogueProtocol.abort(turnId))
@@ -214,8 +229,11 @@ class DialogueClient(
private fun send(text: String): Boolean { private fun send(text: String): Boolean {
checkMainThread() checkMainThread()
val current = socket ?: return false val current = socket
if (!ready || released) return false if (current == null || !ready || released) {
connectionLog("ws control skipped: not ready", "error")
return false
}
if (current.send(text)) return true if (current.send(text)) return true
connectionLog("ws send failed", "error") connectionLog("ws send failed", "error")
finish(current, ConnectionStatus.DISCONNECTED) finish(current, ConnectionStatus.DISCONNECTED)
@@ -291,7 +309,10 @@ class DialogueClient(
onProtocolError("Invalid binary frame") onProtocolError("Invalid binary frame")
return@dispatch return@dispatch
} }
DebugLogUpload.log("audio", "downlink frame turn=${frame.turnId} seq=${frame.sequence} bytes=${frame.pcm16.size}") if (loggedAudioTurn != frame.turnId) {
loggedAudioTurn = frame.turnId
DebugLogUpload.log("audio", "downlink started turn=${frame.turnId}")
}
onFrame(frame) onFrame(frame)
} }