我从Application到Fragment类这样调用方法:
ChatApplication app = (ChatApplication) getActivity().getApplication();
mSocket = app.getSocket();
,我得到了mSocket
的连接。 如何使用Service代替Application来实现相同功能? Fragment需要套接字连接才能启动其他操作。我需要连接才能处于服务状态,而不是处于Fragment或其他状态。
ChatApplication.java
package com.github.nkzawa.socketio.androidchat;
import android.app.Application;
import io.socket.client.IO;
import io.socket.client.Socket;
import java.net.URISyntaxException;
public class ChatApplication extends Application {
private Socket mSocket;
{
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
mSocket.connect();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Socket getSocket() {
return mSocket;
}
}
MainFragment.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
ChatApplication app = (ChatApplication) getActivity().getApplication();
mSocket = app.getSocket();
startSignIn();
}