首页 > 解决方案 > 如何重新连接服务中始终存在的websocket?

问题描述

问题是我正在尝试创建 a service,在其中我提出了 a 的连接WebSocket,这样service它就不会死掉,并且Websocket我创建的那个也会发生同样的事情。

问题是我创建了WebSocket并且当我完成执行它并且没有连接时它结束,并且它不会尝试自行连接。

WebSocket我的问题是,如果连接失败或互联网存在与否,我该如何再次尝试连接?

这是我的代码:

主要活动,我开始我的service

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    startService(new Intent(this,ConnectionService.class));
}

}

BroadcastReceiver

public class NetworkState extends BroadcastReceiver {
@SuppressLint("UnsafeProtectedBroadcastReceiver")
@Override
public void onReceive(Context context, Intent intent) {
    context.startService(new Intent(context,ConnectionService.class));
}

}

我的service

public class ConnectionService extends IntentService {
private final String SERVER_URL = "ws://10.0.2.2:9000";
private ServerConnection mServerConnection;

public ConnectionService() {
    super("ConnectionService");
}

public int onStartCommand(Intent intent, int flags, int startId){
    return START_STICKY;
}

@Override
protected void onHandleIntent(Intent intent) {
    mServerConnection = new ServerConnection(SERVER_URL);
    mServerConnection.connect();
}

}

WebSocket班级:

public class ServerConnection {

private WebSocket mWebSocket;
private OkHttpClient mClient;
private String mServerUrl;

private class SocketListener extends WebSocketListener {
    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        Log.i(TAG,"ERROR");
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        Log.i(TAG,"ERROR");
    }

    @Override
    public void onClosed(WebSocket webSocket, int code, String reason) {
        Log.i(TAG,"ERROR");
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        Log.i(TAG,"ERROR");
        connect();
    }
}

public ServerConnection(String url) {
    mClient = new OkHttpClient.Builder()
            .readTimeout(3,  TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .build();

    mServerUrl = url;
}

public void connect() {
    Request request = new Request.Builder()
            .url(mServerUrl)
            .build();
    mWebSocket = mClient.newWebSocket(request, new SocketListener());
}

public void disconnect() {
    mWebSocket.cancel();
}

}

我的AndroidManifest:

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name=".QueryService"
        android:exported="false" />

    <receiver
        android:name=".NetworkState"
        android:permission="@string/test">
        <intent-filter>
            <action android:name="com.example.queryservicesocket.ConnectionService" />
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

    <service
        android:name=".ConnectionService"
        android:exported="false"/>
</application>

标签: androidservicewebsocketbroadcastreceiver

解决方案


推荐阅读