简体   繁体   中英

How to pass asynctask to another activity in android?

I'm try to writing an online game with a socket connection. So I use asynctask to make a socket connection.

SocketServer.java

public class SocketServer{

private MyCustomListener listener;

private String ip = "127.0.0.1";
private int port = 4444;

@SuppressWarnings("unused")
private Context context;
private SocketAsync socketAsync;
private String dataInput, username;

public SocketServer(Context context) {
    this.context = context;
}

public void setOnRecieveMsgListener(MyCustomListener listener) {
    this.listener = listener;
}

public void connect() {
    socketAsync = new SocketAsync();
    socketAsync.execute();
}

public void sentData(String x, String y, String z) {
    dataInput = null;
    JSONObject object = new JSONObject();
    // JSON Encode
    socketAsync.sentJSON(object);
}

private class SocketAsync extends AsyncTask<Void, Void, String> {

    private Socket socket;
    private PrintWriter printWriter;

    @Override
    protected String doInBackground(Void... params) {
        try {
            socket = new Socket(InetAddress.getByName(ip),port);
            OutputStreamWriter streamOut = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
            printWriter = new PrintWriter(streamOut);
            streamOut.flush();
            BufferedReader streamIn = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
            Looper.prepare();
            while(socket.isConnected()) {
                try {
                    dataInput = streamIn.readLine();
                    listener.onRecieveMessage(new MyListener(dataInput));
                }
                catch(Exception e) {}
            }
            Looper.loop();
        }
        catch(Exception e) {}
        return null;
    }

    public void sentJSON(JSONObject object) {
        if(socket.isConnected()) {
            try {
                printWriter.println(object.toString());
                printWriter.flush();
            }
            catch(Exception e) {}
        }
    }

}
}

Login.class

public class Login extends Activity implements MyCustomListener {

JSONObject object;
SocketServer socketserver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    socketserver = new SocketServer(this);
    socketserver.setOnRecieveMsgListener(this);
    socketserver.connect();
    button();
}

private void button() {
    Button loginBt = (Button)findViewById(R.id.login_bt);
    final EditText un = (EditText)findViewById(R.id.username);
    final EditText ps = (EditText)findViewById(R.id.password);
    final String[] logindata = new String[2];

    loginBt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            logindata[0] = un.getText().toString();
            logindata[1] = ps.getText().toString();
            socketserver.setUsername(logindata[0]);
            socketserver.sentData("SERVER", "TEST", "login");
        }
    });
}

private void toMainScreen() {
    Intent x = new Intent(this,Main.class);
    startActivity(x);
}

@Override
public void onRecieveMessage(MyListener ml) {
    try {
        JSONObject json = new JSONObject(ml.getMsgStr());
        System.out.println(json.getString("content"));
        if(json.getString("content").equals("TRUE")) {
            toMainScreen();
        }
        else
            Toast.makeText(getApplicationContext(), "Login Fail", Toast.LENGTH_SHORT).show();
    } catch (JSONException e) {
        Log.e("## JSON DECODE", e.toString());
        e.printStackTrace();
    }
}
}

Main.class

public class Main extends Activity implements MyCustomListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //do some thing
}

@Override
public void onRecieveMessage(MyListener ml) {
    System.out.println("MAIN : " + ml.getMsgStr());
}
}

so how can I pass object "socketserver" from login class to main class? or is there an other way to do something like this?

sorry for my poor english.

You should not try to pass an instance of SocketServer around. One of it's properties is context which means you should not used it outside the original context it was created in (ie activity it was created in) or you'll have memory leaks.

Your SocketServer class needs IP and port. This is the kind of information that you should pass between activities and then use that to create another instance of your SocketServer class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM