2014-02-17 148 views
0

我正嘗試使用套接字連接編寫在線遊戲。 所以我使用asynctask來建立套接字連接。如何將asynctask傳遞給android中的另一個活動?

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()); 
} 
} 

所以我怎麼能傳遞對象 「的SocketServer」 從登錄類主要課程? 還是有其他方式來做這樣的事情嗎?

對不起我的英文不好。

+0

最簡單的方法是爲AsyncTask製作一個泛化類並在需要的地方調用它們 – Kunu

+0

請看看這個http://stackoverflow.com/questions/3821423/background-task-progress-dialog-orientation-change- is-there-any-100-working/3821998#3821998 – 2014-02-17 04:44:54

+0

將'socketserver'對象傳遞給Main.class之後,您希望從該'socketserver'對象中檢索什麼? –

回答

0

你不應該試着通過一個SocketServer的實例。其中一個屬性是上下文,這意味着您不應該在創建它的原始上下文之外(即創建它的活動)使用它,否則您會有內存泄漏。

您的SocketServer類需要IP和端口。這是您應該在活動之間傳遞的那種信息,然後使用它來創建SocketServer類的另一個實例。

相關問題