连接到服务器重启应用程序

时间:2016-10-18 18:35:48

标签: java android

我在计算机上安装了Java服务器,在Android手机上安装了客户端。 但是,当我启动应用程序并转到处理客户端的活动时,它会将应用程序重新启动回第一个活动。执行客户端方法时会发生这种情况。

客户端代码是这个

public class ServerInterface extends Activity {

private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String message = "test1";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_server_interface);

    sendCommand("test");




}

public void sendCommand(String command) {
try {


    client = new Socket("192.168.100.50", 43596);  //Connect to PC server
    printwriter = new PrintWriter(client.getOutputStream(), true);
    printwriter.write(command);  

    printwriter.flush();
    printwriter.close();
    client.close();   //closing the connection

} catch (UnknownHostException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
 }

我不知道这里出了什么问题。 感谢。

1 个答案:

答案 0 :(得分:1)

您必须在异步线程中运行网络。 Android不允许它在主线程上(在你要使用它的类中的位置)

private class Connect extends AsyncTask<String, Integer, Boolean> {
     protected Boolean doInBackground(String... urls) {
         try {


        client = new Socket("192.168.100.50", 43596);  //Connect to PC server
        printwriter = new PrintWriter(client.getOutputStream(), true);
        printwriter.write(command);  

        printwriter.flush();
        printwriter.close();
        client.close();   //closing the connection

    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
         return false;
     }


 }

然后进行联网:

new Connect().execute("nullable unless used for dynamic links");
相关问题