Detect desktop disconnects on Android

This commit is contained in:
Misaka
2026-05-17 14:21:09 +08:00
parent 7cd6fbd1f2
commit 1286a63507

View File

@@ -18,10 +18,13 @@ import okhttp3.Response
import okhttp3.WebSocket import okhttp3.WebSocket
import okhttp3.WebSocketListener import okhttp3.WebSocketListener
import org.json.JSONObject import org.json.JSONObject
import java.util.concurrent.TimeUnit
class ConnectionService : Service() { class ConnectionService : Service() {
private val tag = "WTS" private val tag = "WTS"
private val client = OkHttpClient() private val client = OkHttpClient.Builder()
.pingInterval(5, TimeUnit.SECONDS)
.build()
override fun onBind(intent: Intent?): IBinder? = null override fun onBind(intent: Intent?): IBinder? = null
@@ -103,6 +106,7 @@ class ConnectionService : Service() {
Log.d(tag, "Ignoring stale WebSocket onClosed") Log.d(tag, "Ignoring stale WebSocket onClosed")
return return
} }
currentSocket = null
updateState(connected = false, connecting = false, host = host, port = port, lastError = null) updateState(connected = false, connecting = false, host = host, port = port, lastError = null)
Handler(Looper.getMainLooper()).post { Handler(Looper.getMainLooper()).post {
stopForeground(STOP_FOREGROUND_REMOVE) stopForeground(STOP_FOREGROUND_REMOVE)
@@ -115,12 +119,18 @@ class ConnectionService : Service() {
Log.d(tag, "Ignoring stale WebSocket onFailure") Log.d(tag, "Ignoring stale WebSocket onFailure")
return return
} }
currentSocket = null
val errorMessage = if (state.connected) {
"桌面端服务已断开"
} else {
t.message ?: "连接失败"
}
updateState( updateState(
connected = false, connected = false,
connecting = false, connecting = false,
host = host, host = host,
port = port, port = port,
lastError = t.message ?: "连接失败" lastError = errorMessage
) )
Handler(Looper.getMainLooper()).post { Handler(Looper.getMainLooper()).post {
stopForeground(STOP_FOREGROUND_REMOVE) stopForeground(STOP_FOREGROUND_REMOVE)
@@ -243,7 +253,17 @@ class ConnectionService : Service() {
} }
} }
.toString() .toString()
return socket.send(payload) val sent = socket.send(payload)
if (!sent && currentSocket == socket) {
currentSocket = null
updateState(
connected = false,
connecting = false,
lastError = "连接已断开"
)
}
return sent
} }
fun stateMap(): Map<String, Any?> { fun stateMap(): Map<String, Any?> {