我試圖測試我的Android應用程序是否連接到Rpi熱點。我正在關注客戶端代碼this guide。Android套接字連接測試
我想根據socket.isConnected()的狀態彈出一個Toast消息,當我點擊一個按鈕時。不過,我認爲每次我嘗試並實施它時,我都會遇到Network上的主線程問題。我如何更改以下代碼以使用onClick中的isConnected方法添加簡單的「if(true),send toast message」?
謝謝你的幫助! Thread.So你寫上這是造成問題的主要線插座(網絡操作)
package mrxhaleenterprise.sockettest;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private Socket socket;
private static final int SERVERPORT = 39169;
private static final String SERVER_IP = "172.24.1.1";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
可以分享錯誤日誌嗎? – Kaushal28