gpt4 book ai didi

android - 如何在后台保持任务?

转载 作者:行者123 更新时间:2023-11-30 00:21:56 26 4
gpt4 key购买 nike

我在我的 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连接不上!

最佳答案

您必须运行 Service 才能保持连接有效。

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);

关于android - 如何在后台保持任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46128028/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com