How to programmatically check availibilty of internet connection in Android?

Fahad picture Fahad · Dec 25, 2010 · Viewed 28.4k times · Source

I want to check programmatically whether there is an internet connection in Android phone/emulator. So that once I am sure that an internet connection is present then I'll make a call to the internet.

So its like "Hey emulator! If you have an internet connection, then please open this page, else doSomeThingElse();"

Answer

Christoph Haefner picture Christoph Haefner · Dec 25, 2010

The method I implemented for myself:

/*
 * isOnline - Check if there is a NetworkConnection
 * @return boolean
 */
protected boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
        return true;
    } else {
        return false;
    }
}

Be aware of that this is a NetworkConnection-Check. If there is a NetworkConnection it doesn't have to be a InternetConnection.