Reputation: 95
My Websocket client (OkHttp) doesn't close the connection after the app closed. It opens a new connection every time I open the app which makes the app suffering from multiple messages received on the old and the new Websocket connections from the broadcasting server.
Is that a normal behavior for the android client, as for what I have experienced with web-client, the session was closed properly after the tab killed?
I have been looking up the problem across the internet but no luck so far. I want to make sure whether it happened because of my bad code logic or just the buggy Websocket's implementation from the library?
Here is how I start a new websocket session in the main Activity
var request: Request = Request.Builder()
.url("ws://$serverIP:8080/example/sim/speed")
.build()
var webSocketListener: WebSocketListener = object : WebSocketListener() {
override fun callback(msg: Message) {
updateSpeed(msg.content)
}
override fun onClosing(webSocket: WebSocket?, code: Int, reason: String?) {
super.onClosing(webSocket, code, reason)
}
}
var webSocket = client!!.newWebSocket(request, webSocketListener)
After that updateSpeed()
will update a text view on UIThread
The onClosed
event was not triggered when the app closed but only when the close
function called manually.
I'm sure that it opened a new socket every time because I can see new sessions created on the server with different ports.
What I want is to have the app closing its connection before it was closed.
Thank you
Upvotes: 3
Views: 3480
Reputation: 7817
You should be aware that if users swipe to remove your app from the Android Task Switch panel (accessible from the square button), you app gets killed immediately, and App.onDestroy doesn't get called. :-/
Upvotes: 0
Reputation: 6788
I also encountered this issue, that WebSocket was still opened after my app was killed.
To solve this issue I manually close socket and remove all idle connections:
fun clear() {
webSocket?.close(1001, "Android: User exited the game.")
webSocket = null
subs.clear()
subs.add(Completable.fromAction {
client.connectionPool.evictAll()
}.subscribeOn(Schedulers.io()).subscribe({}, {}))
}
And I basically call clear()
inside activity/ies, that might be opened during app kill.
override fun onDestroy() {
super.onDestroy()
App.webSocketClient().clear()
}
Not an ideal solution, but works every time.
Upvotes: 1