One of my apps uses a lot of HTTP requests to communicate with its back-end. I use 2 different implementations to perform these requests:
- The library
Volley
for most cases - A combination of
AsyncTask
andDefaultHttpClient
for few cases
Most of the time, everything works well. But sometimes I have a bunch of network exceptions raised and shown into Crashlytics:
java.net.UnknownHostException: Unable to resolve host "mydomain.com": No address associated with hostname Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
com.android.volley.ServerError at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:175) at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:110)
With a bit of research, I found that this is supposed to happen when the device has a really bad 3g/4g or behind a VPN/subnetwork so it can't reach my website.
How do I make sure the device is really connected to internet? I actually perform these requests only if this function return true:
public static boolean isOnline(Context ctx) {
ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
Or should I just let it go and assume it is normal to get up to few hundreds of these warning per month?
In order to see if you have internet you have to do something more than check if you have a network connection. Because if your connected to a slow network, captive portal or a VPN you have a connection to the network but no actual internet or usable internet.
That's why you still need to check if you have internet/usable internet before you make a HTTP request by adding a simple ping to a server or Google (Because Google is up 99,99% of the time). You can also do it periodically or when you catch the first exception, that's up to you.
You can also use another method but the general idea is the same use something you know is almost always online and check if you can reach it.
However keep handling exceptions, because there is no way to always catch it and having a back up way of handling things can't hurt