0

When I use my code in HTC Wildfire S (API10, android 2.3.3), this works fine. But if I run on Samsung Galaxy S4 (API19, android 4.4.2), it doesn't work (application starts and closes; nothing happens). The server is on my local computer (Hercules Program). Of course I added the permission (INTERNET) in manifest.

The code is:

try{
    Socket s = new Socket("192.168.1.13", 6914);
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
    String outMsg = "";
    outMsg = "This is Client";
    out.write(outMsg);
    out.flush();
    out.close();
    s.close();
} catch (IOException e) {
    e.printStackTrace();
}

So could you help me and show where the problem is? I didn't root my Samsung phone.

sam
  • 2,780
  • 1
  • 17
  • 30
  • Are you running this code from the main thread? Do you have any log? – Marc Plano-Lesay Jan 11 '15 at 13:57
  • I just read about it ("This will lead to your app being unresponsive. Before Honeycomb you could get away with it, but Honeycomb and newer Android versions will check and throw the exception you're getting"), so i think i shouldn't run this in main thread. I run this in MainActivity without thread. So this is the problem? Now i can't see the logs. – user3681087 Jan 11 '15 at 14:02
  • Yes, this is the problem. I'll detail it in an answer. – Marc Plano-Lesay Jan 11 '15 at 14:23

1 Answers1

0

It appears like you're running network-related code in the main (UI) thread. On Android 1.x and 2.x, it was not recommended because it could cause the UI to freeze. Since Android 3.x (and it's still valid in Android 4.x and 5.0), it's now strictly forbidden by the platform. You'll get a NoNetworkInMainThreadException if you have any chance to read the logs.

To achieve this kind of test, I would recommend you to use a Thread:

new Thread() {
    public void run() {
        // Your network code, it will run on another thread
    }
}.start();

If you need to get the result back on your main thread (which you will probably need at some point), you'll want to take a look at a more complex pattern like AsyncTask.

Marc Plano-Lesay
  • 6,808
  • 10
  • 44
  • 75