android.permission.ACCESS_WIFI_STATE 触发这么多完整的状态

android.permission.ACCESS_WIFI_STATE triggers so many complete states

在我的广播接收器中,我使用以下代码来识别 Wifi 是否已连接或断开。它工作完美,但 wifiInfo.getSupplicantState().equals(SupplicantState.COMPLETED) returns 在连接 wifi 时至少有 4 到 7 次为真。

我可以使用 SupplicantState.ASSOCIATING 因为它似乎只触发一次吗?

WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if(wifiManager.isWifiEnabled()){
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    if( wifiInfo.getSupplicantState().equals(SupplicantState.COMPLETED)){ //Connected ??
        //Do Something
    }
    else if( wifiInfo.getSupplicantState().equals(SupplicantState.DISCONNECTED)){       
        //Do Something
    }
}
else{
    //Wifi Adaptor disabled;
}

这是我用于 BroadCast Receiver 的 intent-filter

<receiver
    android:name="WifiReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="android.net.wifi.STATE_CHANGE"/>
    </intent-filter>
</receiver>

不,您不能使用,因为来自 ASSOCIATING

的文档

Trying to associate with a BSS/SSID. This state is entered when wpa_supplicant has found a suitable BSS to associate with and the driver is configured to try to associate with this BSS in ap_scan=1 mode. When using ap_scan=2 mode, this state is entered when the driver is configured to try to associate with a network using the configured SSID and security policy.

表示正在进行中。 另外,如果您考虑 ASSOCIATED

Association completed. This state is entered when the driver reports that association has been successfully completed with an AP. If IEEE 802.1X is used (with or without WPA WPA2), wpa_supplicant remains in this state until the IEEE 802.1X/EAPOL authentication has been completed.

所以这些都是完全没有连接wifi AP的状态。
所以,最好的就是只用COMPLETED
为了处理重复的回调,使用一个布尔值,它在 if 块中为 true,在 else 中为 false block.And 仅当它为 false 时才会进入 if 块。