I'm trying to connect two emulators in android,one is considered the server and one the client. I use a text view and a handler to post the state of client and the server. The problem with my client is that I can get to create the socket and usually I get an error message posted on the text view.Not only that,but when I try to press buttons on the client app I get force close and I don't know why cause I have a different thread for client's connection:)
Can someone please tell me what I'm doing wrong?
Here is my code:
public class screen1 extends Activity {
private TextView clientState;
private String serverIpAddress="10.0.2.2";
public static final int ClientPort = 8080;
private boolean connected = false;
private Handler handler=new Handler();
Socket socket;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen1);
clientState = (TextView) findViewById(R.id.client_Status);
Button b = (Button)findViewById(R.id.mainMenu);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(screen1.this, screen2.class);
startActivity(i);
}
});
Thread cThread=new Thread(new ClientThread());
cThread.start();
}
public class ClientThread implements Runnable{
public void run()
{
try
{
InetAddress serverAddr=InetAddress.getByName(ser开发者_如何学GoverIpAddress);
handler.post(new Runnable(){
public void run(){
clientState.setText(" try to connect!");
}
});
socket=new Socket(serverAddr,ClientPort);
handler.post(new Runnable(){
public void run(){
clientState.setText("Connected!");
}
});
}
catch(Exception e){
handler.post(new Runnable(){
public void run(){
clientState.setText("Error");
}
});
e.printStackTrace();
}
}
}
protected void onStop() {
super.onStop();
try {
// make sure you close the socket upon exiting
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'm not good at Android programming, but I see that you're entering an infinite loop in your code:
while(true){
handler.post(new Runnable(){
public void run(){
clientState.setText("Connected!");
}
});
}
精彩评论