I am using this code to check if a WiFi or mobile network is connected.
private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
}
return false;
}
This works fine. But what if my user is on a prepaid plan but doesn’t have any credit for data? This method will still return true if data is enabled but my app will crash when it tries to download data from a server. How can I check for something like this?
I guess there are also other things that can halt my app accessing a server even when a wifi/mobile network is available.
As a mobile platform, internet access on Android is inherently unreliable. As you are starting to realise, you should be writing your app so it is tolerant of intermittent data access.
You are catching some exceptions, but not handling them – that means that your app will continue past the exception as though it didn’t happen, and then crashes because your httpClient object is in an invalid state and is likely throwing new exceptions, which you are not catching.