簡體   English   中英

連接到服務器會重新啟動應用程序

[英]Connecting to server restarts application

我在計算機上設置了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();
}
 }

我不知道這里出了什么問題。 謝謝。

您必須在異步線程中運行網絡。 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");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM