我正在尝试使用以下代码连接打开的Wifi network
:
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + SSID + "\"";
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
int netid = wifiManager.addNetwork(conf);
wifiManager.saveConfiguration();
if(netid != -1){
wifiManager.enableNetwork(netid,true);
}
Wifi使用上述代码连接100%
次,但需要很长时间才能连接。 enableNetwork
方法会在true
wifi连接后立即返回20-40 seconds
。我也试过wifimanager.reconnct()
但没有运气。
答案 0 :(得分:0)
此方法连接到您的wifi - networkSSID - 您的网络ssid和networPass是您的网络密码
private void connect(String networkSSID ,String networkPass )
{
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\"";
if (scanResult.capabilities.contains("WEP")) {
conf.wepKeys[0] = "\"" + networkPass + "\"";
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
}
else if (scanResult.capabilities.contains("WPA")) {
conf.preSharedKey = "\"" + networkPass + "\"";
}
else
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
break;
}
}
}