在Android中通过代码切换到指定 WiFi
权限
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
代码
/**
*
* @param context
* @param ssid 带引号的ssid "\"wifi_name\""
* @param password wifi 密码
* @param fuzzyMatch 是否模糊匹配ssid
*/
private void changeWifi(Context context, String ssid, String password, boolean fuzzyMatch) {
WifiManager wifiManager = getWifiManager(context);
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for (WifiConfiguration wifiConfiguration : list) {
String wifiSSID = wifiConfiguration.SSID;
boolean ssidMatch = fuzzyMatch ? wifiSSID.startsWith(ssid) : wifiSSID.equals(ssid);
if (ssidMatch) {
if (!TextUtils.isEmpty(password)) {
wifiConfiguration.preSharedKey = "\"" + password + "\"";
}
wifiManager.disconnect();
wifiManager.enableNetwork(wifiConfiguration.networkId, true);
wifiManager.reconnect();
break;
}
}
}