Android - 连接到已知的隐藏Wi-Fi网络

时间:2015-08-12 09:20:07

标签: android wifi hidden

我需要以编程方式连接到隐藏的Wi-Fi网络。 我知道它的SSID,安全类型和密码。 出于某种原因,我无法连接它。

如果没有隐藏,我可以连接到同一个网络。

这是我的代码:

// configure the network
private void saveWPANetwork(WiFiNetwork network){ 

WifiConfiguration conf = new WifiConfiguration(); 
conf.SSID =network.getSSID(); 
conf.hiddenSSID = true; 
conf.status = WifiConfiguration.Status.ENABLED; 
conf.preSharedKey =network.getPassword(); 
conf.priority = 9999; 
wifi.addNetwork(conf); 
wifi.saveConfiguration(); 
}

// connect it
protected boolean connectToVaildNetwork() { 

List<WifiConfiguration> list = wifi.getConfiguredNetworks(); 
if(list == null) 
return false; 

for( WifiConfiguration i : list ) { 
for (WiFiNetwork network : config.wiFiNetworksDetails) { 
if(network.getSSID().equalsIgnoreCase(i.SSID)){ 
wifi.enableNetwork(i.networkId, true); 
return wifi.reconnect(); /// STRANGE BUT IT ALWAYS RETURNS TRUE, EVEN IF 
DEVICE IS NOT CONNECTED TO THE 
HIDDEN NETWORK! 
} 
} 
} 
return false; 
}

1 个答案:

答案 0 :(得分:5)

这个答案可能会迟到但我还是会在有需要的情况下发布。 Android 4.4.2测试过。注意隐藏的网络需要更长的时间来连接(我的测试大约是10-15秒)

wifi.reconnect()== true表示您的命令已成功请求,并不表示已连接wifi。

public void setWifiConfig(String ssid, String sharedKey) {
    WifiConfiguration conf = new WifiConfiguration();
    conf.SSID = "\"" + ssid + "\"";   // Please note the quotes. String should contain ssid in quotes

    conf.preSharedKey = "\"" + sharedKey + "\"";

    conf.hiddenSSID = true;
    conf.status = WifiConfiguration.Status.ENABLED;
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);

    WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);

    wifiManager.addNetwork(conf);

    List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
    for (WifiConfiguration i : list) {
        if (i.SSID != null && i.SSID.equals("\"" + ssid + "\"")) {

            wifiManager.disconnect();

            wifiManager.enableNetwork(i.networkId, true);

            wifiManager.reconnect();

            wifiManager.saveConfiguration();
            break;
        }
    }
}