Search code examples
androidandroid-wifiokhttp

Detecting loss of WiFi connection in OkHttp3


When OkHttp3 calls the onFailure callback, it passes an IOException. Is there a specific subclass of IOException that will indicate that the target device has disappeared from the WiFi network? Is there another way to detect this?


Solution

  • IOException has several sub-classes; while it may be save to assume that something went offline - because when the own network connection is still alive, it has to be the other side of the connection. when it throws an IOException, that's an IOExcpetion; casting it won't add any more information.

    the state of the own network connection can be detected, but not with OkHttp3. here's an example for that on my GitHub; see class ConnectivityListener and class ConnectivityReceiver.

    How would you detect the state of another host's network connection? this can be tested, by switching off the WiFi network of either device; both situations would cause an IOException.