Ton
Ton

Reputation: 9736

Wifi getSSID() returns null

I use getSSID() to get the name of the wifi network as soon as a new connection is made. But sometimes I get null for that value. This is my code:

Permissions in manifest are correct, because, as I said, most of the times it works.

I use this filter for the broadcast receiver:

<action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />

In the broadcast I do this:

if("android.net.wifi.supplicant.CONNECTION_CHANGE".equals(intent.getAction()))
{  boolean bConected = intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false);
   if(bConnected == true)
   {  WifiManager wifi = (WifiManager) Contexto.getSystemService(Context.WIFI_SERVICE);
      String MyName = wifi.getConnectionInfo().getSSID();
      Sometimes MyName is null here even if Wifi is connected correctly
   }
}

Any ideas?

Upvotes: 1

Views: 4064

Answers (3)

BitBot
BitBot

Reputation: 508

I've found out the hard way that the supplicant subsystem is only relevant to the WPA security mechanism, and is really not a good choice to use for monitoring general wifi connection status. The verbiage in the documentation would lead you to believe that it's possible, but I had a lot of trouble when trying to use the supplicant actions, including issues similar to the one you describe.

From the SupplicantState enum documenation:

These enumeration values are used to indicate the current wpa_supplicant state. This is more fine-grained than most users will be interested in. In general, it is better to use NetworkInfo.State.

Using the NETWORK_STATE_CHANGED_ACTION and looking at the NetworkInfo extra I was able to get expected, stable behavior.

Upvotes: 0

Halim Qarroum
Halim Qarroum

Reputation: 14103

The Android Developers website states that :

The SSID may be null if there is no network currently connected.

You're listening to a CONNECTION_CHANGE event, what if the state of the connection changed from connected to disconnected ?

Wifi devices gets sometimes disconnected from an access point and they do reconnect silently without you even noticed it was disconnected.

Upvotes: 3

David Manpearl
David Manpearl

Reputation: 12656

I use similar code regularly and I have never received null when connected.

Here is my code:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
String myName = info.getSSID();

Therefore, I propose that you should wait 400 to 1000ms or so after receipt of the CONNECTION_CHANGE broadcast before requesting the information.


Here is one example that will implement the delay:

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        String myName = info.getSSID();
    }
}, 1000);

Upvotes: 5

Related Questions