Check if internet is available

4 votes · 2 comments

This function will return true if you can access the internet (or false if you can't). You can change the parameter being return when roaming (read the comments).

raw ·
· download
/* * @return boolean return true if the application can access the internet */ private boolean haveInternet(){ NetworkInfo info = ((ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); if (info==null || !info.isConnected()) { return false; } if (info.isRoaming()) { // here is the roaming option you can change it if you want to disable internet while roaming, just return false return true; } return true; }
Add a comment


I think it is: NetworkInfo info = (NetworkInfo) getSystemService(CONNECTIVITY_SERVICE);

Reply · March 14, 2011, 3:49 p.m.

The correct line would be:

NetworkInfo info = ((ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE)).

The only change are the brackets around the cast and until .getActiveNetworkInfo().

Edit: Thanks, the snippet was updated accordingly.

Reply · March 14, 2011, 3:59 p.m.