Programmatic connection to open WiFi network fails intermittently on Android 9

59 Views Asked by At

I'm building a product where we use a board running Android 9. One of the programs I am building has to connect to a specific WiFi device without user interactions. Most of the time it connects with no problem, but sometimes it refuses to connects whatsoever. Here is the code I use:

public static boolean connectToWifiNetwork(String networkSSID, String networkPassword) {

        if (networkSSID == null || networkSSID.equals("")) return false;
        Log.v(TAG, "connected name: " + getConnectedWifiName());
        if(getConnectedWifiName() != null && getConnectedWifiName().equals(networkSSID))return true;

        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain ssid in quotes

        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        conf.allowedAuthAlgorithms.clear();
        conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        conf.priority = 400000; //4000;
        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);

                Log.v(TAG, "Trying to connect");
               wifiManager.reconnect();
                wifiManager.reassociate();
                wifiManager.reconnect();
                wifiManager.reassociate();
               try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        }


        if (checkWifiConnection().equals(WifiState.CONNECTED)) return true;

        return false;

It is worth noting that this WiFi device is open (meaning no password). Also, I can connect to that device using my personal phone with no problems.

Any ideas how to solve this issue?

I tried to change the way I connect to the WiFi device, but that didn't change the outcome.

0

There are 0 best solutions below