我在 android 中的聊天应用程序中使用 WebSockets。为了方便起见,我在 Application 类中创建连接,以便它可以由具有一个实例的活动和片段使用。这是我的应用程序类的代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
由于某种原因,套接字在 onPause 或 onDestroy 中都没有关闭(都尝试过)。我在服务器端使用 Ratchet。这段代码有什么问题?请注意,我想完全从应用程序类本身关闭连接,而不是从活动或片段或任何其他组件关闭连接。
答案可能是WebSocketActivity extends FragmentActivity implements WebSocketListener {}因为Activity会实现这些生命周期方法,因此它们可以被重写。
| 归档时间: |
|
| 查看次数: |
445 次 |
| 最近记录: |