在Android应用程序中,可以使用OkHttp库来创建并管理Websocket连接,并将其封装在Service中以确保连接的稳定性。以下是一个示例代码:
public class WebSocketService extends Service {
private static final String TAG = WebSocketService.class.getSimpleName();
private static final String WS_URL = "ws://iot-device-url"; // IOT设备的Websocket URL
private static final int NORMAL_CLOSURE_STATUS = 1000;
private WebSocket webSocket;
@Override
public void onCreate() {
super.onCreate();
connectWebSocket();
}
@Override
public void onDestroy() {
super.onDestroy();
disconnectWebSocket();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null; // 不需要绑定到Activity
}
private void connectWebSocket() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(WS_URL).build();
webSocket = client.newWebSocket(request, new WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Response response) {
Log.d(TAG, "WebSocket连接成功");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
Log.d(TAG, "收到消息:" + text);
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
webSocket.close(NORMAL_CLOSURE_STATUS, null);
Log.d(TAG, "WebSocket即将关闭");
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
Log.d(TAG, "WebSocket已关闭");
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
Log.e(TAG, "WebSocket连接失败:" + t.getMessage());
// 尝试重新连接
connectWebSocket();
}
});
}
private void disconnectWebSocket() {
if (webSocket != null) {
webSocket.close(NORMAL_CLOSURE_STATUS, "Service被销毁");
}
}