From ee4d87113f2a558eb888fd1cef96534bb522427c Mon Sep 17 00:00:00 2001 From: Jannis Mattheis Date: Sun, 4 Nov 2018 09:12:44 +0100 Subject: [PATCH] Fix websocket connection on refresh On refresh the service was restarted but the connection wasn't closed, therefore each incoming message was handled n times. --- .../github/gotify/service/WebSocketConnection.java | 12 +++++++++--- .../com/github/gotify/service/WebSocketService.java | 5 +++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/github/gotify/service/WebSocketConnection.java b/app/src/main/java/com/github/gotify/service/WebSocketConnection.java index c6914fb..650156d 100644 --- a/app/src/main/java/com/github/gotify/service/WebSocketConnection.java +++ b/app/src/main/java/com/github/gotify/service/WebSocketConnection.java @@ -36,6 +36,7 @@ public class WebSocketConnection { private BadRequestRunnable onBadRequest; private OnFailureCallback onFailure; private Runnable onReconnected; + private boolean isClosed; WebSocketConnection(String baseUrl, String token) { this.baseUrl = baseUrl; @@ -84,6 +85,7 @@ public class WebSocketConnection { public synchronized WebSocketConnection start() { close(); + isClosed = false; Log.i("WebSocket: starting..."); webSocket = client.newWebSocket(request(), new Listener()); @@ -92,6 +94,8 @@ public class WebSocketConnection { public synchronized void close() { if (webSocket != null) { + Log.i("WebSocket: closing existing connection."); + isClosed = true; webSocket.close(1000, ""); webSocket = null; } @@ -124,11 +128,13 @@ public class WebSocketConnection { @Override public void onClosed(WebSocket webSocket, int code, String reason) { - Log.w("WebSocket: closed"); - synchronized (this) { - onClose.run(); + if (!isClosed) { + Log.w("WebSocket: closed"); + onClose.run(); + } } + super.onClosed(webSocket, code, reason); } diff --git a/app/src/main/java/com/github/gotify/service/WebSocketService.java b/app/src/main/java/com/github/gotify/service/WebSocketService.java index ab5777d..8feb227 100644 --- a/app/src/main/java/com/github/gotify/service/WebSocketService.java +++ b/app/src/main/java/com/github/gotify/service/WebSocketService.java @@ -58,6 +58,11 @@ public class WebSocketService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.init(this); + + if (connection != null) { + connection.close(); + } + Log.i("Starting " + getClass().getSimpleName()); super.onStartCommand(intent, flags, startId); new Thread(this::startPushService).run();