Wifi getSSID() returns null

China☆狼群 提交于 2021-01-29 04:08:11

问题


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?


回答1:


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);



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/15709422/wifi-getssid-returns-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!