我的应用程序中有 2 个按钮。
按钮 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 = new Button.OnClickListener() {
public void onClick(View v) {
WifiConnect();
}
};
Button.OnClickListener buttonConnectOnClickListener = new 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 = new 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();
}
}
}
};
`
看起来我创建套接字的线程没有在这里调用,不知道为什么。