protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ipEditText = findViewById(R.id.ipEditText); portEditText = findViewById(R.id.portEditText); Button connectButton = findViewById(R.id.connectButton); connectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String ip = ipEditText.getText().toString(); int port = Integer.parseInt(portEditText.getText().toString()); new ConnectTask().execute(ip, String.valueOf(port)); } }); Button sendMessageButton = findViewById(R.id.sendMessageButton); sendMessageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showSendMessageDialog(); } }); }出现E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.rlswj, PID: 16184 android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1668) at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:116) at java.net.SocketOutputStream.write(SocketOutputStream.java:161) at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221) at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291) at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:295) at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:141) at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:229) at java.io.BufferedWriter.flush(BufferedWriter.java:254) at java.io.PrintWriter.newLine(PrintWriter.java:482) at java.io.PrintWriter.println(PrintWriter.java:629) at java.io.PrintWriter.println(PrintWriter.java:670)
时间: 2024-02-26 11:52:23 浏览: 182
Android this与Activity.this的区别
这个错误信息与你之前提到的错误信息相同,都是由于在主线程中进行了网络操作导致的。你需要将网络操作放到单独的线程或使用异步任务来执行,例如在 `ConnectTask` 中执行网络操作,而不是在主线程中执行。在 `ConnectTask` 的 `doInBackground` 方法中执行网络操作,然后在 `onPostExecute` 方法中更新 UI。
阅读全文