必须在不同的活动中调用singleton socketIO类吗?

时间:2014-09-26 05:52:03

标签: java android sockets android-layout websocket

我正在使用gottox-socket.io库进行socket编程。我已经为socket创建了singleton类。我可以在主要活动中调用它,但我无法将其称为其他活动....这是我的单身类..

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

    }
}

1 个答案:

答案 0 :(得分:0)

您是否考虑过在帮助程序包中创建一个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{
        }
    }
}