我正在使用gottox Socket.IO库进行套接字编程。我已经为socket创建了单例类。我可以在主活动中调用它,但不能在另一个活动中调用它。
public class MainActivity extends Activity {
EditText uname, passwd;
Button login;
JSONObject json;
SocketIOClient socket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
socket = new SocketIOClient();
try {
SocketIOClient.initInstance();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
json = new JSONObject();
uname = (EditText) findViewById(R.id.unameED);
passwd = (EditText) findViewById(R.id.passwdED);
login = (Button) findViewById(R.id.loginButton);
login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
json.put("username", uname.getText().toString().trim());
json.put("password", passwd.getText().toString().trim());
//request send to server
SocketIOClient.emit("login_request", json);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
} 此外,我还使用抽象类将json存储库从单例类转换为activity。下面是我的抽象类
public abstract class ResponseHandler
{
private Context context;
public abstract void execute (JSONObject jsonObject) throws JSONException;
public ResponseHandler (Context ctx)
{
this.context = ctx;
}
public void handleObject(JSONObject jsonObject) throws Exception
{
execute(jsonObject);
}
}发布于 2014-09-26 15:04:56
你有没有想过在帮助包中创建一个GlobalClass (例如:com.project.name.helpers),并从那里调用它。喜欢
public class GlobalClass extends Activity {
public static SocketIOClient socket = new SocketIOClient();
}然后,您可以在导入GlobalClass后从您的活动中调用它,因为它是一个已经创建的静态类,如下所示:
import com.project.name.helpers;
public SomeActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
GlobalClass.socket.initInstance();
}
catch{
}
}
}https://stackoverflow.com/questions/26052894
复制相似问题