1

建立新连接后,我使用 getSSID() 获取 wifi 网络的名称。但有时我会为该值获得 null 。这是我的代码:

清单中的权限是正确的,因为正如我所说,大多数情况下它都有效。

我将此过滤器用于广播接收器:

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

在广播中,我这样做:

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
   }
}

有任何想法吗?

4

3 回答 3

5

null我经常使用类似的代码,但在连接时我从未收到过。

这是我的代码:

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

因此,我建议您在收到CONNECTION_CHANGE广播后等待 400 到 1000ms 左右再请求信息。


这是一个将实现延迟的示例:

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);
于 2013-03-29T18:51:46.607 回答
3

Android 开发者网站指出:

如果当前没有连接网络,SSID 可能为空。

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.

于 2013-03-29T18:52:37.297 回答
0

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.

于 2016-03-29T16:32:31.033 回答