android application crashes if no internet
I am using this code to check the network availability for the android application.
public boolean isOnline(Context ctx) {
ConnectivityManager conMgr = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo i = conMgr.getActiveNetworkInfo();
if (i == null)
return false;
if (!i.isConnected())
return false;
if (!i.isAvailable())
开发者_运维问答 return false;
return true;
}
But if am connect to a WiFi network but no internet is accessible in that network then how I will check that internet is not available, actually my application crashes and I want to show alert box instead of crashing the application!
Does somebody know how to check internet availability?
This is error log:
http://licrp.dnsalias.net:8000/iteam/images/error.jpg
If you just want to be sure that you are connected to wifi and have an internet connection you could just ping a known adress, for example google which is usually online :)
URL url = new URL("http://www.google.com");
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
int responseCode = conn.getResponseCode();
//if responseCode = 200 - THEn CONN is connected
精彩评论