jasdefer
jasdefer

Reputation: 25

Android socket app crash

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?

Upvotes: 0

Views: 3400

Answers (1)

user_CC
user_CC

Reputation: 4776

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

Upvotes: 3

Related Questions