0

I want my app to connect to a server. I only want the client.

protected void onCreate(Bundle savedInstanceState) {
    //...
    try {
             InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
             socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);

    } catch (UnknownHostException e1) {
         //... 
    } catch (IOException e1) {
         //...
    }
}

But the application just crashes. I started this activity by pressing a button. Do you know what the problem could be?

Charles
  • 50,943
  • 13
  • 104
  • 142
jasdefer
  • 25
  • 1
  • 7
  • 2
    use Thread or AsyncTask to perform Network operation in other Thread instead of Main UI Thread – ρяσѕρєя K Mar 22 '13 at 11:12
  • 1
    Beside the point that @ρяσѕρєяK is right, _please_ add some log information to the next question you have or, better, just read it! – WarrenFaith Mar 22 '13 at 11:14
  • The first comment is probably right, but in addition you could get exceptions from permissions as well. To find problems like this see the DDMS tab in eclipse and see the stack trace (then maybe post it here). – hack_on Mar 22 '13 at 11:15
  • possible duplicate of [android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – Selvin Mar 22 '13 at 11:26
  • Thank you very much and sorry for the bad question. They say on developer.android.com/reference/android/os/AsyncTask.html that you shouldnt use async task for a long period of time. What should I use for long term usage. (I want to send geo tracking data every 10 seconds or something to my server – jasdefer Mar 25 '13 at 10:21

1 Answers1

3

You need to perform all your blocking processes in a Thread, and release the main UI Thread, for example:

protected void onCreate(Bundle savedInstanceState) {
    //...
    new Thread(){
        public run(){
            try {
                InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
                socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
            } catch (UnknownHostException e1) {
                //... 
            } catch (IOException e1) {
                //... 
            }
        }
    }.start();
}
Teocci
  • 7,189
  • 1
  • 50
  • 48
user_CC
  • 4,686
  • 3
  • 20
  • 15
  • 1
    Thank you very much. They say on http://developer.android.com/reference/android/os/AsyncTask.html that you shouldnt use async task for a long period of time. What should I use for long term usage. (I want to send geo tracking data every 10 seconds or something to my server) – jasdefer Mar 25 '13 at 10:20