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.
This commit is contained in:
Jannis Mattheis
2018-11-04 09:12:44 +01:00
parent ca0194e3bb
commit ee4d87113f
2 changed files with 14 additions and 3 deletions

View File

@@ -36,6 +36,7 @@ public class WebSocketConnection {
private BadRequestRunnable onBadRequest; private BadRequestRunnable onBadRequest;
private OnFailureCallback onFailure; private OnFailureCallback onFailure;
private Runnable onReconnected; private Runnable onReconnected;
private boolean isClosed;
WebSocketConnection(String baseUrl, String token) { WebSocketConnection(String baseUrl, String token) {
this.baseUrl = baseUrl; this.baseUrl = baseUrl;
@@ -84,6 +85,7 @@ public class WebSocketConnection {
public synchronized WebSocketConnection start() { public synchronized WebSocketConnection start() {
close(); close();
isClosed = false;
Log.i("WebSocket: starting..."); Log.i("WebSocket: starting...");
webSocket = client.newWebSocket(request(), new Listener()); webSocket = client.newWebSocket(request(), new Listener());
@@ -92,6 +94,8 @@ public class WebSocketConnection {
public synchronized void close() { public synchronized void close() {
if (webSocket != null) { if (webSocket != null) {
Log.i("WebSocket: closing existing connection.");
isClosed = true;
webSocket.close(1000, ""); webSocket.close(1000, "");
webSocket = null; webSocket = null;
} }
@@ -124,11 +128,13 @@ public class WebSocketConnection {
@Override @Override
public void onClosed(WebSocket webSocket, int code, String reason) { public void onClosed(WebSocket webSocket, int code, String reason) {
Log.w("WebSocket: closed");
synchronized (this) { synchronized (this) {
onClose.run(); if (!isClosed) {
Log.w("WebSocket: closed");
onClose.run();
}
} }
super.onClosed(webSocket, code, reason); super.onClosed(webSocket, code, reason);
} }

View File

@@ -58,6 +58,11 @@ public class WebSocketService extends Service {
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
Log.init(this); Log.init(this);
if (connection != null) {
connection.close();
}
Log.i("Starting " + getClass().getSimpleName()); Log.i("Starting " + getClass().getSimpleName());
super.onStartCommand(intent, flags, startId); super.onStartCommand(intent, flags, startId);
new Thread(this::startPushService).run(); new Thread(this::startPushService).run();