Search code examples
androidandroid-intentandroid-wifi

WifiInfo SSID null directly after WIFI_STATE_ENABLED received


When WIFI_STATE_ENABLED is received by my BroadcastReceiver directly after that the SSID value of WifiInfo is null. However it works when I add a Thread.Sleep() for 800 milliseconds. There seems to be a delay in the event connecting the wifi and the WifiInfo object actually getting the information. The snippet below works:

    else if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
        int extraWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
        switch (extraWifiState) {
        case WifiManager.WIFI_STATE_ENABLED:
            // The SSID is null just after connection is established. This
            // event seems over eager.
            try {
                Thread.sleep(800, 0);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (!wifiFunctions.connectedToGConnectHotspot()) {
                removeConnectedNotification();
            } else {
                settings.setLastNotificationTime(System.currentTimeMillis());
                notifyUserOfAvailableHotspot(true);
                return;
            }
            break; 

That works but it is extremely dodgy. What if it takes longer on some devices? Is there another way to get the connected SSID. I looked and EXTRA_NETWORK_INFO but it is deprecated as of API level 14 and also does not seem to include the SSID anyway. Is there another method to get the SSID without introducing an artificial wait?


Solution

  • WIFI_STATE_ENABLED is not the action you want to capture if you're looking to get the SSID. The one you might be more interested is NETWORK_STATE_CHANGED.

    The WIFI_STATE_ENABLED occurs when the WiFi device on the phone is switched on - it's not necessarily connected anywhere at that point.

    Edit: as pointed out in the comments, NETWORK_STATE_CHANGED triggers on many other events too. For strictly monitoring connection to WiFi access point, SUPPLICANT_CONNECTION_CHANGE_ACTION is the correct action to listen.