如何从我的SocketService类访问方法到MainFragment类以返回已建立套接字连接(mSocket
)的方法。
我需要在Service中而不是在Fragment中启动连接,方法如何知道该连接处于活动状态?
SocketService.java
public int onStartCommand(Intent intent, int flags, int startId) {
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
mSocket.connect();
mSocket.on("new message", onNewMessage);
}
return START_STICKY;
}
这是我想在Fragment中调用的方法
public Socket getSocket() {
return mSocket.connect();
}
如何告知Fragment服务已经建立连接
MainFragment.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// ChatApplication app = (ChatApplication) getActivity().getApplication();
SocketService app = (SocketService) getActivity().getApplication();
mSocket = app.getSocket();
mSocket.on(Socket.EVENT_CONNECT,onConnect);
mSocket.on(Socket.EVENT_DISCONNECT,onDisconnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.on("new message", onNewMessage);
Intent intent = new Intent(getActivity(), SocketService.class);
getActivity().startService(intent);
// mSocket.connect();
startSignIn();
}