I have server and client code that works perfectly as a Java application. The server is run on my local machine and listens on port 4444. Any Java application can connect easily, but when I move my code over to Android, I keep getting an IOException no matter what I try. I read that you have to change "localhost" to "10.0.2.2", but I'm still getting an IOException. I tried my IP address from whatsmyip.org but it still gives me an IOException. Here's my android code...
package test.myPackage;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class TestProjectActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
tv.setText("Hello, Android");
setContentView(tv);
Socket s = null;
try {
s = new Socket("10.0.2.2", 4444);
tv.setText("socket: CONNECTED!");
} catch (UnknownHostException e) {
tv.setText("socket: unknown host");
} catch (IOException e) {
tv.setText("socket: IO Exception");
}
}
}
First make sure your app has internet permission.
The only time you can use the 10.0.2.2 alias is if your app is running on an emulator and wants to contact something running on the hosting machine. This does not work with actual android devices.
For an actual android device, you would either have to put the device on the same wifi network as the PC hosting the server, find a way to abuse a tethering solution to get them on the same network over the USB cable, or move your server to a machine externally accessible from the Internet at large in order to be able to reach it from the device's mobile network connection.
And EvilDuck definitely has a point about abusing the UI thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With