Search code examples
androidbroadcastreceiverandroid-wifi

Detect when WiFi network fails to authenticate


I am trying to connect to a WiFi network using WiFiManager. Here is the code I use to do so :

WifiManager manager = [...];
WifiConfiguration config = new WifiConfiguration();
manager.setWifiEnabled(true);

//Set SSID, PSK, etc...
[...]

//Connect to the network
int netId = manager.addNetwork(config);
if (netId == -1)
{
    Toast.makeText(this, "Invalid PSK", Toast.LENGTH_LONG).show();
    return;
}
manager.enableNetwork(netId, true);
manager.saveConfiguration();

Beforehand, I registered a BroadcastReceiver for the WifiManager.NETWORK_STATE_CHANGED_ACTION action. I'm trying to detect when the connection succeeds or fails (for various reasons including authentication) by checking the DetailedState of the given NetworkInfo.

Everything works when the connection succeeds, but for some reason my receiver isn't "executed" when the connection fails. The network is added to the device's list, I can see it by going into WiFi Settings, but it does not try to connect (or it does try to connect but doesn't notify my receiver).

Any clue ? Thanks !


Solution

  • I finally managed to achieve what I wanted.

    To detect that the connection succeeded, register the WifiManager.NETWORK_STATE_CHANGED_ACTION broadcast intent and check for the NetworkInfo.DetailedState.OBTAINING_IPADDR detailed state (for WiFi obviously).

    To detect that the connection failed, register the WifiManager.SUPPLICANT_STATE_CHANGED_ACTION broadcast intent and check for any WifiManager.EXTRA_SUPPLICANT_ERROR integer extra (typically WifiManager.ERROR_AUTHENTICATING). You may need to gain access for Android hidden API to achieve that.