我在我的Android应用程序中使用socket.io。即使关闭应用程序,我也希望保持连接活动并且永远不会关闭。我创建了一个这样的服务类:
public class MyService extends Service {
private static Socket socket;
{
try {
socket = IO.socket("http://192.168.1.52:2500");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
socket.connect();
return Service.START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
在我的主类中使用此代码:
Intent intent = new Intent(this,MyService.class);
startService(intent);
但Socket没有连接!
答案 0 :(得分:1)
您必须运行服务才能使您的连接保持活动状态。
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
connectSocket()
return Service.START_STICKY;
}
private void connectSocket() {
try {
IO.Options options = new IO.Options();
options.reconnection = true;
socket = IO.socket("http://192.168.1.52:2500", options);
socket.on(Socket.EVENT_CONNECT, onConnected);
socket.on(Socket.EVENT_CONNECT_ERROR, onConnectionError);
socket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectionTimout);
socket.on(Socket.EVENT_DISCONNECT, onDisconnect);
socket.on("Event_Key", eventCallback );
socket.connect();
} catch (URISyntaxException e) {
Log.d(getClass().getSimpleName(), "Socket Connection Exception");
e.printStackTrace();
}
private Emitter.Listener onConnected = new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.d("SocketIO","onConnected");
}
};
private Emitter.Listener onConnectionError = new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.d("SocketIO","onConnectionError");
if (!closeSocket)
socket.connect();
}
};
private Emitter.Listener onConnectionTimout = new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.d("SocketIO","onConnectionTimout");
if (!closeSocket)
socket.connect();
}
};
private Emitter.Listener onDisconnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.d("SocketIO","onDisconnect");
if (!closeSocket)
socket.connect();
}
};
private Emitter.Listener eventCallback = new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.d("SocketIO", "Result: "+ String.valueOf(args[0]);
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
服务将在Backgourd中运行,直到您停止或系统停止它为止。
启动服务如下:
Intent intent = new Intent(this, MyService.class);
startService(intent);