I am trying to connect to a specific wifi network, as described here. However, while sometimes it works, most of the times it doesn't. I do not really understand why if I run the app, let's say 10 times, the device connects to my network 2 times, and the other 8 it doesn't.
In the following is the code I use in a Fragment.
WifiConfiguration wificonfiguration = new WifiConfiguration();
wificonfiguration.SSID = "\"" + networkSSID + "\"";
wificonfiguration.priority = 40;
wificonfiguration.status = WifiConfiguration.Status.ENABLED;
// WPA management
wificonfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wificonfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wificonfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wificonfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wificonfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wificonfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wificonfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wificonfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wificonfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wificonfiguration.preSharedKey = "\"" + networkPass + "\"";
WifiManager wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
int networkId = wifiManager.addNetwork(wificonfiguration);
if (networkId > -1) {
boolean status = wifiManager.enableNetwork(networkId, true);
}
The network configuration is actually added to the manager and status
value is true. I have run it on several devices running Lollipop. Also, the network I want to connect to does not provide internet access, so I also thought that may be a problem for what stated in the note here. Can anybody tell me if the code is ok?
Solved
The problem was solved by adding wifiManager.disconnect();
before adding the new network configuration.
答案 0 :(得分:0)
您可以在添加网络之前通过下述方法禁用所有网络。这将禁用所有已配置的网络以自动连接。
$_FILES