Detect desktop disconnects on Android
This commit is contained in:
@@ -18,10 +18,13 @@ import okhttp3.Response
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
class ConnectionService : Service() {
|
||||
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
|
||||
|
||||
@@ -103,6 +106,7 @@ class ConnectionService : Service() {
|
||||
Log.d(tag, "Ignoring stale WebSocket onClosed")
|
||||
return
|
||||
}
|
||||
currentSocket = null
|
||||
updateState(connected = false, connecting = false, host = host, port = port, lastError = null)
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
@@ -115,12 +119,18 @@ class ConnectionService : Service() {
|
||||
Log.d(tag, "Ignoring stale WebSocket onFailure")
|
||||
return
|
||||
}
|
||||
currentSocket = null
|
||||
val errorMessage = if (state.connected) {
|
||||
"桌面端服务已断开"
|
||||
} else {
|
||||
t.message ?: "连接失败"
|
||||
}
|
||||
updateState(
|
||||
connected = false,
|
||||
connecting = false,
|
||||
host = host,
|
||||
port = port,
|
||||
lastError = t.message ?: "连接失败"
|
||||
lastError = errorMessage
|
||||
)
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
@@ -243,7 +253,17 @@ class ConnectionService : Service() {
|
||||
}
|
||||
}
|
||||
.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?> {
|
||||
|
||||
Reference in New Issue
Block a user