I am using WebSockets for my chat app in android. For convenience, I am creating the connection in Application class so that it can be used by activities and fragments with one instance. Here is the code for my Application class:
public class Main extends Application implements LifecycleObserver {
private static WeakReference<Context> context;
private WebSocket webSocket;
private final Request request;
private final OkHttpClient client;
public static final int SOCKET_CLOSE_CODE = 1000;
@Override
public void onCreate() {
super.onCreate();
context = new WeakReference<>(getApplicationContext());
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
this.client = new OkHttpClient();
this.request = new Request.Builder().url("ws://192.168.1.9:8080").build();
}
public void connect() {
webSocket = client.newWebSocket(request, new WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Response response) {
super.onOpen(webSocket, response);
}
@Override
public void onMessage(WebSocket webSocket, String text) {
super.onMessage(webSocket, text);
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
super.onMessage(webSocket, bytes);
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
super.onClosing(webSocket, code, reason);
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
super.onClosed(webSocket, code, reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
super.onFailure(webSocket, t, response);
}
});
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
if (webSocket == null) return;
connect();
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
if (webSocket == null) return;
disconnect();
}
private void disconnect() {
webSocket.close(SOCKET_CLOSE_CODE, null);
webSocket = null;
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
if (client == null) return;
client.connectionPool().evictAll();
client.dispatcher().executorService().shutdown();
}
}
For some reason, the socket does not close in either onPause or onDestroy (tried both). I am using Ratchet in server side. What's wrong with this code? Note that I want to close the connection exactly from the Application class itself instead of closing from activities or fragments or any other components.
from WebSockets not closing on onPause/onStop [okhttp] - Android
No comments:
Post a Comment