Android套接字应用崩溃

时间:2013-03-22 11:10:01

标签: android sockets client-server

我希望我的应用连接到服务器。我只想要客户。

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

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

但应用程序崩溃了。我按下按钮开始了这项活动。 你知道问题是什么吗?

1 个答案:

答案 0 :(得分:3)

您需要在线程中执行所有阻塞过程,并释放主UI线程,例如:

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