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:
@@ -3,6 +3,7 @@ package com.gorios.lanvoice
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Bundle
|
||||
import android.security.NetworkSecurityPolicy
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
@@ -21,6 +22,7 @@ import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
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.ExpressionStatus
|
||||
import com.gorios.lanvoice.expression.ExpressionUiState
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
private var state by mutableStateOf(VoiceUiState())
|
||||
@@ -56,18 +59,23 @@ class MainActivity : ComponentActivity() {
|
||||
else if (!granted) expressions.permissionDenied()
|
||||
}
|
||||
private val microphonePermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
val shouldStart = pendingStart
|
||||
pendingStart = false
|
||||
if (granted && shouldStart) session.startVoice()
|
||||
else if (!granted) session.permissionDenied()
|
||||
DebugLogUpload.log("audio", "microphone permission granted=$granted foreground=$inForeground")
|
||||
if (granted) startPendingVoice()
|
||||
else {
|
||||
pendingStart = false
|
||||
session.permissionDenied()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
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(
|
||||
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) },
|
||||
)
|
||||
expressions = ExpressionController(this, this) { expressionState = it }
|
||||
@@ -88,6 +96,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private fun toggleVoice() {
|
||||
DebugLogUpload.log("audio", "voice button active=${state.voiceActive}")
|
||||
if (state.voiceActive) {
|
||||
pendingStart = false
|
||||
session.stopVoice()
|
||||
@@ -95,28 +104,42 @@ class MainActivity : ComponentActivity() {
|
||||
session.startVoice()
|
||||
} else if (!pendingStart) {
|
||||
pendingStart = true
|
||||
DebugLogUpload.log("audio", "microphone permission requested")
|
||||
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() {
|
||||
super.onStart()
|
||||
inForeground = true
|
||||
DebugLogUpload.log("connect", "activity onStart")
|
||||
connectionLogs = emptyList()
|
||||
session.foreground()
|
||||
startPendingVoice()
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
inForeground = false
|
||||
val permissionInFlight = pendingStart || pendingCamera
|
||||
DebugLogUpload.log("connect", "activity onStop permission=$permissionInFlight changingConfig=$isChangingConfigurations")
|
||||
pendingCamera = false
|
||||
expressions.stop()
|
||||
pendingStart = false
|
||||
session.background()
|
||||
if (!permissionInFlight) pendingStart = false
|
||||
session.background(keepConnectionForPermission = permissionInFlight)
|
||||
super.onStop()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
expressions.release()
|
||||
DebugLogUpload.log("connect", "activity onDestroy changingConfig=$isChangingConfigurations")
|
||||
session.release()
|
||||
super.onDestroy()
|
||||
}
|
||||
@@ -131,6 +154,12 @@ fun Home(
|
||||
val gold = Color(0xFFE8C884)
|
||||
val muted = Color(0xFF9CA3AF)
|
||||
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)) {
|
||||
Column(
|
||||
modifier = Modifier.align(Alignment.TopCenter).padding(top = 24.dp),
|
||||
@@ -154,7 +183,7 @@ fun Home(
|
||||
modifier = Modifier.background(Color(0xFF242433), RoundedCornerShape(50))
|
||||
.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()) {
|
||||
Text(
|
||||
text = connectionLogs.takeLast(3).joinToString("\n"),
|
||||
|
||||
@@ -29,6 +29,7 @@ class VoiceSession(
|
||||
private var state = VoiceUiState()
|
||||
private var foreground = false
|
||||
private var released = false
|
||||
private var backgroundTimeout: Runnable? = null
|
||||
private var captureEpoch = 0L
|
||||
private var capturing = false
|
||||
private var currentTurn = 0L
|
||||
@@ -66,16 +67,34 @@ class VoiceSession(
|
||||
fun foreground() {
|
||||
checkMainThread()
|
||||
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
|
||||
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()
|
||||
foreground = 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() {
|
||||
@@ -90,6 +109,7 @@ class VoiceSession(
|
||||
/** Activity verifies runtime permission first; capture still handles permission revocation. */
|
||||
fun startVoice() {
|
||||
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 (!dialogue.listen(true)) return
|
||||
update(state.copy(voiceActive = true, phase = VoicePhase.LISTENING, guidance = null))
|
||||
@@ -142,6 +162,7 @@ class VoiceSession(
|
||||
if (!isActive() || capturing) return
|
||||
capturing = true
|
||||
val epoch = ++captureEpoch
|
||||
DebugLogUpload.log("audio", "capture start")
|
||||
capture.start(
|
||||
onFrame = { pcm ->
|
||||
main.post {
|
||||
|
||||
@@ -12,6 +12,10 @@ import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import okhttp3.Response
|
||||
import org.json.JSONObject
|
||||
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.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
@@ -23,12 +27,15 @@ object DebugLogUpload {
|
||||
private val tags = setOf("connect", "ws", "auth", "audio", "error")
|
||||
private val pending = AtomicInteger()
|
||||
private val launchSent = AtomicBoolean()
|
||||
@Volatile var lastResult: String = "等待发送"
|
||||
private set
|
||||
private val json = "application/json; charset=utf-8".toMediaType()
|
||||
// Build independently, never newBuilder() from the voice client. HTTP-only avoids
|
||||
// initializing TLS for the diagnostic channel whose purpose includes TLS failures.
|
||||
private val client by lazy {
|
||||
OkHttpClient.Builder()
|
||||
.connectionSpecs(listOf(ConnectionSpec.CLEARTEXT))
|
||||
.proxy(Proxy.NO_PROXY) // Direct LAN request, independent of any system HTTP proxy.
|
||||
.connectionPool(ConnectionPool(2, 30, TimeUnit.SECONDS))
|
||||
.dispatcher(Dispatcher().apply { maxRequests = 2; maxRequestsPerHost = 2 })
|
||||
.connectTimeout(3, TimeUnit.SECONDS)
|
||||
@@ -41,8 +48,11 @@ object DebugLogUpload {
|
||||
.build()
|
||||
}
|
||||
|
||||
fun appLaunch(version: String) {
|
||||
if (launchSent.compareAndSet(false, true)) log("connect", "app_launch version=$version")
|
||||
fun appLaunch(version: String, cleartextPermitted: Boolean = true) {
|
||||
if (!cleartextPermitted) lastResult = "系统禁止网关明文 HTTP"
|
||||
if (launchSent.compareAndSet(false, true)) {
|
||||
log("connect", "app_launch version=$version cleartext=$cleartextPermitted")
|
||||
}
|
||||
}
|
||||
|
||||
fun log(tag: String, message: String) {
|
||||
@@ -61,16 +71,28 @@ object DebugLogUpload {
|
||||
.toString().toRequestBody(json)
|
||||
client.newCall(Request.Builder().url(ENDPOINT).post(body).build()).enqueue(object : Callback {
|
||||
override fun onFailure(call: Call, error: IOException) {
|
||||
lastResult = "上传失败:${failureSummary(error)}"
|
||||
pending.decrementAndGet() // No retries, recursive logs or UI updates.
|
||||
}
|
||||
|
||||
override fun onResponse(call: Call, response: Response) {
|
||||
lastResult = "HTTP ${response.code}"
|
||||
try { response.close() } catch (_: Exception) { }
|
||||
finally { pending.decrementAndGet() }
|
||||
}
|
||||
})
|
||||
} catch (_: Exception) {
|
||||
} catch (error: Exception) {
|
||||
lastResult = "上传失败:${failureSummary(error)}"
|
||||
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 authReceived = false
|
||||
private var helloSent = false
|
||||
private var loggedAudioTurn: Long? = null
|
||||
private var handshakeTimeout: Runnable? = null
|
||||
|
||||
fun connect() {
|
||||
checkMainThread()
|
||||
check(!released) { "DialogueClient has been released" }
|
||||
if (hasActiveConnection()) {
|
||||
connectionLog("connect skipped: session active", "connect")
|
||||
return
|
||||
}
|
||||
generation++
|
||||
connectionLog("connect_start #$generation", "connect")
|
||||
cancelHandshakeTimeout()
|
||||
@@ -84,6 +89,7 @@ class DialogueClient(
|
||||
wsOpened = false
|
||||
authReceived = false
|
||||
helloSent = false
|
||||
loggedAudioTurn = null
|
||||
healthCall?.cancel()
|
||||
healthCall = null
|
||||
socket?.cancel()
|
||||
@@ -107,6 +113,11 @@ class DialogueClient(
|
||||
startHealthProbe(attempt)
|
||||
}
|
||||
|
||||
fun hasActiveConnection(): Boolean {
|
||||
checkMainThread()
|
||||
return !released && (socket != null || healthCall != null)
|
||||
}
|
||||
|
||||
private fun startHealthProbe(attempt: Long) {
|
||||
healthPhase = "health request"
|
||||
try {
|
||||
@@ -192,7 +203,11 @@ class DialogueClient(
|
||||
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))
|
||||
|
||||
@@ -214,8 +229,11 @@ class DialogueClient(
|
||||
|
||||
private fun send(text: String): Boolean {
|
||||
checkMainThread()
|
||||
val current = socket ?: return false
|
||||
if (!ready || released) return false
|
||||
val current = socket
|
||||
if (current == null || !ready || released) {
|
||||
connectionLog("ws control skipped: not ready", "error")
|
||||
return false
|
||||
}
|
||||
if (current.send(text)) return true
|
||||
connectionLog("ws send failed", "error")
|
||||
finish(current, ConnectionStatus.DISCONNECTED)
|
||||
@@ -291,7 +309,10 @@ class DialogueClient(
|
||||
onProtocolError("Invalid binary frame")
|
||||
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)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user