Android test wifi connection programmatically
Asked Answered
C

3

10

I am programming an Android app for an IoT device. I have to give the device the WiFi username and password, so I am using an android app to do this. I have the following code, but it seems to always connect to the network weather or not the correct password is given.

This I am testing this on the same AP that my phone is connected to.

The desired action is

Disconnect from current AP -> Attempt to connect using credentials given -> Reconnect to original network.

What steps do I need to take to correctly verify a wifi network and password?

code :

WifiConfiguration conf = new WifiConfiguration();
    conf.SSID = "\"" + ssid + "\"";
    for(ScanResult sr: wifiList){
        if(sr.SSID.equals(ssid)){
            if(sr.capabilities.contains("WEP")){
                if(isNumeric(pass)){
                    conf.wepKeys[0] =  pass ;
                }else{
                    conf.wepKeys[0] = "\"" + pass + "\"";
                }
                conf.wepTxKeyIndex = 0;
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            }else if(sr.capabilities.contains("PSK")){
                conf.preSharedKey = "\""+ pass +"\"";
            }else if(sr.capabilities.contains("EAP")){
                wifiName.setError("EAP networks not supported");
                //todo support EAP
            }else{
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            }

            WifiManager wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
            wifiManager.addNetwork(conf);

            List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
            for( WifiConfiguration i : list ) {
                if(i.equals(conf)) {
                    wifiManager.disconnect();
                    if(!wifiManager.enableNetwork(i.networkId, true)){
                        wifiPassword.setError("Incorrect Password");
                        wifiManager.reconnect();
                        return;
                    }else{
                        wifiManager.reconnect();
                        addUser(deviceSN, ssid, pass);
                    }
                }
            }

            break;
        }
    }
Chilon answered 7/2, 2017 at 21:46 Comment(1)
Did you fix this ? I am also facing the issue. If I add the wrong password also return true. So can you suggest the idea to solve this issueNildanile
A
4

You should register to NETWORK_STATE_CHANGED_ACTION.

Using this, you can get the WI-FI network state and you need to check that it reached the connected state. If the device did not reach connected after some timeout, you can assume that the connection has failed.

another helpful receiver might be SUPPLICANT_STATE_CHANGED_ACTION.

public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {

            NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

            switch (info.getState()) {
                case CONNECTING:
                    break;
                case CONNECTED:
                    break;
                case DISCONNECTING:
                    break;
                case DISCONNECTED:
                    break;
                case SUSPENDED:
                    break;
                }
            }
Abbate answered 22/2, 2017 at 10:57 Comment(3)
@iuliu.net Look I think you need to look at getConnectionInfo. developer.android.com/reference/android/net/wifi/…Abbate
Yes but that will not tell you the password... I have the following case: I'm connected to network X, attempt connection to network X with SSID/pw to check for correctness. Then do as you say: "If the device did not reach connected after some timeout, you can assume that the connection has failed.". But the OS just tells me that it's connected to network X no matter what I do since it's already connected..Counterrevolution
I am sorry I am not sure I can help with that one. I don't quite remember the way all the api works.Abbate
A
0

You may don't need to scan for available wifi network, you can easily do like this: follow

public static void connectToWifi(Activity activity, String ssid, String password) {
        WifiConfiguration wifiConfig = new WifiConfiguration();

        wifiConfig.SSID = String.format("\"%s\"", ssid);
        wifiConfig.preSharedKey = String.format("\"%s\"", password);

        WifiManager wifiManager = (WifiManager) activity.getSystemService(WIFI_SERVICE);
        wifiManager.setWifiEnabled(true);
        int netId = wifiManager.addNetwork(wifiConfig);
        wifiManager.disconnect();
        wifiManager.enableNetwork(netId, true);
        wifiManager.reconnect();
    }
Abutting answered 20/2, 2017 at 9:33 Comment(3)
How would I tell if connecting to the network succeeded or failed?Chilon
wifiManager.reconnect(); will return resultant boolean.. whether you are connected or notAbutting
if I add the wrong password also returning the same value.. Can you suggest the solutionNildanile
N
0

Just Check it is like that

public static boolean isConnectingToInternet(Context context){
  try {
      ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null) {
          NetworkInfo info[] = connectivity.getAllNetworkInfo();
          if (info != null) {
              for (int i = 0; i < info.length; i++)

                  if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                      return true;
                  }

          }
      }
  }catch (Exception e){}
    return false;

} 
Nolitta answered 24/2, 2017 at 13:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.