问题
I need to connect to hidden Wi-Fi network programmatically. I know it's SSID, security type and password. For some reason I can't connect it.
I can connect to the same network if it's not hidden.
Here's my code:
// 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:
This answer maybe late but I still post it in case of someone need. Android 4.4.2 tested. Notes that hidden networks take longer time to connect (for my test it was around 10-15s)
wifi.reconnect() == true means that your command has been requested successfully, it does not mean that wifi is connected.
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;
}
}
}
来源:https://stackoverflow.com/questions/31960984/android-connect-to-known-hidden-wi-fi-network