我在我的應用程序中有2個按鈕。Wifi連接和套接字客戶端在一個按鈕中點擊probem
按鈕1:連接wifi的 按鈕2:創建一個客戶端套接字
與個人2個按鈕此功能工作。
void WifiConnect() { String networkSSID = "HI-LINK_DA79"; String networkPass = "12345678"; WifiConfiguration conf = new WifiConfiguration(); conf.SSID = "\"" + networkSSID + "\""; //ssid must be in quotes conf.preSharedKey = "\""+ networkPass +"\"";
WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
int r1 =-1;
r1= wifiManager.addNetwork(conf);
Log.d("Client", "add Network returned " + r1);
boolean b = wifiManager.enableNetwork(r1, true);
Log.d("Client", "enableNetwork returned " + b);
boolean d= wifiManager.reconnect();
Log.d("Client", "wifiManager.reconnect() returned " + d)
}
`Button.OnClickListener buttonWifiConnectOnClickListener =新Button.OnClickListener(){
public void onClick(View v) {
WifiConnect();
}
};
Button.OnClickListener buttonConnectOnClickListener =新Button.OnClickListener(){
public void onClick(View v) {
if (socket == null) {
Log.i("Client", "socket():Creating --");
new Thread(new ClientThread()).start();
//connect.setText("Disconnect");
}
else
{
try {
socket.close();
socket=null;
Log.i("Client", "socket():closed --");
// connect.setText("Connect");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
`
但這,如果我在一個按鈕,結合他們點擊 `Button.OnClickListener buttonConnectOnClickListener =新Button.OnClickListener(){
public void onClick(View v) {
WifiConnect(); //WiFi connect
if (socket == null) {
Log.i("Client", "socket():Creating --");
new Thread(new ClientThread()).start();
//connect.setText("Disconnect");
}
else
{
try {
socket.close();
socket=null;
Log.i("Client", "socket():closed --");
// connect.setText("Connect");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
`
看起來像我的線程創建不工作套接字不在這裏調用,不知道爲什麼。
在其他問題中,您將收到一個NetworkOnMainThread異常,用於在UI事件方法中執行套接字操作。 –