pooja
pooja

Reputation: 179

How to test wifi connection using given ssid and password and returns result of whether given ssid and password is correct or not

I want to test wifi connection through android app to check whether entered wifi ssid and password is correct or not. How i can check whether the given ssid and password is correct?

Upvotes: 1

Views: 1634

Answers (1)

MidasLefko
MidasLefko

Reputation: 4559

Here's what we do in our app:

  1. We ensure that the wifi is enabled
  2. We create a WifiConfiguration with the ssid and pw (note that WifiConfiguration.SSID and WifiConfiguration.preSharedKey are surrounded in quotes so that if the ssid is example and the pw is password then WifiConfiguration.SSID = "\"example\"" and WifiConfiguration.preSharedKey = "\"password\""
  3. We add the WifiConfiguration to the WifiManager (WifiManager.addNetwork(WifiConfiguration))
  4. We check the return value (which is a networkId) if it is -1 then the operation was not successful
  5. We tell the WifiManager fo enable the networkId from the previous step and attempt to connect (WifiManager.enableNetwork(netId, true))
  6. We check if the negotiation with this WifiConfiguration was successful. This step has some ugly code, and I would love to get some other ideas, but it works:

    private static boolean checkWifiNegotiation(WifiManager wifiManager, int netId) {
        boolean startedHandshake = false;
        boolean successful = false;
    
        for (int i = 0; i < 30; i++) {
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            SupplicantState currentState = wifiManager.getConnectionInfo().getSupplicantState();
            if (!startedHandshake && currentState.equals(SupplicantState.FOUR_WAY_HANDSHAKE)) {
                startedHandshake = true;
            } else if (startedHandshake) {
                if (currentState.equals(SupplicantState.DISCONNECTED)) {
                    break;
                } else if (currentState.equals(SupplicantState.COMPLETED)) {
                    successful = true;
                    break;
                }
            }
            wifiManager.enableNetwork(netId, true);
        }
    
        // no matter what happened above, if COMPLETED then we have the correct pw
        if (!successful && wifiManager.getConnectionInfo().getSupplicantState().equals(SupplicantState.COMPLETED)) {
            successful = true;
        }
    
        return successful;
    }
    

Upvotes: 1

Related Questions