![](/img/trans.png)
[英]Singleton class that show a toast in different activities using resources efficiently
[英]Have to call singleton socketIO class in different activities?
我正在为我的套接字编程使用gottox-socket.io库。 我已经为套接字创建了单例类。 我可以在主要活动中调用它,但不能在其他活动中调用它。这是我的单例课程。
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仓库。 这是我的抽象课
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);
}
}
您是否考虑过在帮助程序包(例如com.project.name.helpers)中创建GlobalClass并从那里调用它。 喜欢
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{
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.