问题描述
我创建了一个 Web 套接字服务.但它一直在建立多个连接
I have created a Web Socket Service. but it keeping making multiple connection
我只希望该应用建立一个连接,除非网络连接断开然后再建立另一个.但是现在,如果我按下手机上的主页按钮,它会建立一个连接.并返回应用程序,它将建立另一个连接.
I just want the app to make one connection, unless the network connection drops then make another.But right now, it makes one connection, if I press the home button on the phone. and go back on the app, it will make another connection.
感谢你们的帮助.
onCreate... 我的 MainActivity
onCreate... of my MainActivity
Intent startServiceIntent = new Intent(this, WebSocketServices.class);
startService(startServiceIntent);
清单
<!-- WebSocket -->
<receiver
android:name="com.example.basicplayerapp.core.NetworkReceiver">
<intent-filter >
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name="com.example.basicplayerapp.core.WebSocketServices"></service>
网络接收器
public class NetworkReceiver extends BroadcastReceiver {
public static final String TAG = HomeActivity.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conn = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = conn.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
Log.i(TAG, "connected");
Intent startServiceIntent = new Intent(context, WebSocketServices.class);
context.startService(startServiceIntent);
}
else if(networkInfo != null){
NetworkInfo.DetailedState state = networkInfo.getDetailedState();
Log.i(TAG, state.name());
}
else {
Log.i(TAG, "lost connection");
}
}//end onReceive
};//end NetworkReceiver
Websocket 服务
public class WebSocketServices extends IntentService {
public static final String TAG = WebSocketServices.class.getSimpleName();
private static String SOCKET_ADDR = "http://171.0.0.1:8080";
private String message = null;
private WebSocket socket = null;
public WebSocketServices() {
super("DownloadService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG, "onHandleIntent");
//SOCKET_ADDR = intent.getStringExtra("ip");
if(socket==null || !socket.isOpen() || socket.isPaused())
connectToPASocket(SOCKET_ADDR);
Log.d(TAG,"Service Invoke Function");
}//end onHandleIntent
//=====================================================================================
// Socket connection
//=====================================================================================
private void connectToPASocket(String SOCKET_ADDR) {
Log.i(TAG, "connectToPASocket()");
// Checking
if (socket != null && socket.isOpen()) return;
// Initiate web socket connection
AsyncHttpClient.getDefaultInstance().websocket(SOCKET_ADDR, null,
new AsyncHttpClient.WebSocketConnectCallback() {
@Override
public void onCompleted(Exception ex, WebSocket webSocket) {
Log.i(TAG, "onCompleted");
if (ex != null) {
Log.i(TAG, "onCompleted > if (ex != null)");
ex.printStackTrace();
return;
}
socket = webSocket;
socket.setStringCallback(new StringCallback() {
public void onStringAvailable(String s) {
Log.i(TAG, "socket.setStringCallback > onStringAvailable - s => " + s);
System.out.println("I got a string: " + s);
message = s;
}// end onStringAvailable
});// end socket.setStringCallback
socket.setDataCallback(new DataCallback() { // Find out what this does
@Override
public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
Log.i(TAG, "socket.setDataCallback > onDataAvailable | emitter=> " + emitter + " | bb => " + bb);
System.out.println("I got some bytes!");
// note that this data has been read
bb.recycle();
}
});// end webSocket.setDataCallback
}// end onCompleted
});// end AsyncHttpClient.getDefaultInstance()
}// end connectToPASocket
}//end WebSocketServices
推荐答案
先生,我也遇到了类似的问题.
MrT, I had a similar probelm.
不要使用意图服务.只需使用服务.因为一旦intentService 完成,它就会自行完成.
Dont use intentService. Just use Service. Because once the intentService has been done, it will finish itself.
在您更改为 Service 后,您可以做的是使用 boolean 检查您的服务是否已启动,如下所示:
After you change to Service, What you can do, is to use boolean to check if your service has been started like so:
boolean isSockeStarted = false;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
...
if (socket == null || !socket.isOpen() || socket.isPaused()) {
if (isSockeStarted) { //not started
} else {
isSockeStarted = true;
}
}
....
也就是说,这个服务只会启动一次.直到你手动杀死它.
That mean, this service will only start once. until you kill it manually.
它对我有用,试着让我知道.
it worked for me, try and let me know.
这篇关于建立多个连接的 Android WebSocket 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!