Search code examples
androidwifimanager

android.permission.ACCESS_WIFI_STATE triggers so many complete states


In my broadcast reciever, I am using the below code to identify if the Wifi is connected or disconnected. It works perfectly, but the wifiInfo.getSupplicantState().equals(SupplicantState.COMPLETED) returns true for atleast 4 to 7 times while connecting wifi.

Can I use SupplicantState.ASSOCIATING as it seems to be triggering only once ?

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

Here is the intent-filter I am using for BroadCast Receiver

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

Solution

  • No,you cant use because from the docs of 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.

    means it is in progress. Also if you think about 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.

    Hence these all are in a state when it is not connected to the wifi AP completely.
    So,the best is only using COMPLETED
    For handling that repeated callback use a boolean which gets true in if block and false in else block.And will go inside if block when it is false only.