我正在尝试连接特定的 wifi,但它无法正常工作。每当我调用下面的代码时,已经连接的 wifi 停止并且手机在扫描模式下显示 wifi。有人可以告诉我为什么会这样。这是我的代码:
String result = "";
try {
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", ssid);
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
int state = wifiManager.getWifiState();
Log.i(TAG, "state: " + state);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String newSSID = wifiInfo.getSSID();
result = "Connected";
} catch (Exception e) {
result = "Failed";
Log.e(TAG, "unable to set wifi " + ssid, e);
}