2

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.

Community
  • 1
  • 1
Emonale
  • 513
  • 2
  • 7
  • 22

1 Answers1

0

You could disable all the network via below described method before adding the network. This would disable all the configured networks to auto-connect.

for (WifiConfiguration wifiConfiguration_ : wifiManager.getConfiguredNetworks()) {

      wifiConfiguration_.status = WifiConfiguration.Status.DISABLED;
      int returnNetworkId_ = wifiManager.updateNetwork(wifiConfiguration_);
}
Rishabh Jain
  • 81
  • 1
  • 5