我正在尝试通过提供SSID和密码来连接到特定的wifi网络。但是,它有时可以工作,但在大多数情况下却不起作用。
我到目前为止尝试过的代码如下(这是针对WPA网络的)。
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = "\"" + networkSSID + "\"";
wifiConfig.preSharedKey = "\"" + networkPass + "\"";
wifiConfig.status = WifiConfiguration.Status.ENABLED;
wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
int netId = mWifiManager.addNetwork(wifiConfig);
mWifiManager.saveConfiguration();
List<WifiConfiguration> configuredNetworks = mWifiManager.getConfiguredNetworks();
if (configuredNetworks != null) {
for (WifiConfiguration existingConfig : configuredNetworks) {
if (existingConfig.SSID.equals(wifiConfig.SSID)) {
mWifiManager.disconnect();
mWifiManager.enableNetwork(existingConfig.networkId, true);
}
}
}
请帮助我修改此代码,以便每当我尝试连接特定的wi-fi网络时都可以使用。