How to programmatically check availibilty of internet connection in Android?

29,484

Solution 1

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.

Solution 2

Being connected to a network does not guarantee internet connectivity.

You might be connected to your home's wifi, but you might not have internet connection. Or, you might be in a restaurant, where you can be connected to the wifi, but still need password for the hotspot in order to use the internet. In such cases the above methods will return true, yet the device wont have internet, and if not surrounded with the right try and catches, the app might crash.

Bottom line, network connectivity, does not mean internet connectivity, it merely means that your device's wireless hardware can connect to another host and both can make a connection.

Below is a method that can check if the device can connect to a website and returns an answer accordingly.

if (networkConnectivity())
{
    try
    {
        HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.anywebsiteyouthinkwillnotbedown.com").openConnection());
        urlc.setRequestProperty("User-Agent", "Test");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(3000); //choose your own timeframe
        urlc.setReadTimeout(4000); //choose your own timeframe
        urlc.connect();
        networkcode2 = urlc.getResponseCode();
        return (urlc.getResponseCode() == 200);
    } catch (IOException e)
    {
        return (false);  //connectivity exists, but no internet.
    }
} else
{
    return false;  //no connectivity
}

Solution 3

as for the question title , you want to check the internet access ,

so the fastest way and it is efficient at least for now ,

thnx to levit based on his answer https://stackoverflow.com/a/27312494/3818437

If you just want to check for a connection to any network - not caring if internet is available - then most of the answers here (including the accepted), implementing isConnectedOrConnecting() will work well. If you want to know if you have an internet connection (as the question title indicates) please read on Ping for the main name servers

 public boolean isOnline() {

     Runtime runtime = Runtime.getRuntime();
     try {

         Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
         int     exitValue = ipProcess.waitFor();
         return (exitValue == 0);

     } catch (IOException e)          { e.printStackTrace(); } 
       catch (InterruptedException e) { e.printStackTrace(); }

     return false; }

That's it! Yes that short, yes it is fast, no it does not need to run in background, no you don't need root privileges.

Possible Questions

Is this really fast enough?

Yes, very fast!

Is there really no reliable way to check if internet is available, other than testing something on the internet?

Not as far as I know, but let me know, and I will edit my answer.

Couldn't I just ping my own page, which I want to request anyways?

Sure! You could even check both, if you want to differentiate between "internet connection available" and your own servers beeing reachable

What if the DNS is down?

Google DNS (e.g. 8.8.8.8) is the largest public DNS service in the world. As of 2013 it serves 130 billion requests a day. Let 's just say, your app not responding would probably not be the talk of the day.

Which permissions are required?

Just internet access - what surprise ^^ (Btw have you ever thought about, how some of the methods suggested here could even have a remote glue about the availablility of internet, without this permission?)

Solution 4

i have been using these two methods to check internet status sometimes https protocol doesn't work try http protocol

// Check if network is available
public static boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager)
            AppGlobals.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isConnected();
}

// ping the google server to check if internet is really working or not
public static boolean isInternetWorking() {
    boolean success = false;
    try {
        URL url = new URL("https://google.com");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(10000);
        connection.connect();
        success = connection.getResponseCode() == 200;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return success;
}

if http does not work its because of the new android security they donot allow plain text communication now. for now just to by pass it.

android:usesCleartextTraffic="true"

Solution 5

Try this:

ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

if(connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED || connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING  ) {
   text.setText("hey your online!!!")     ;               
   //Do something in here when we are connected   
} else if(connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||  connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED   ) {
   text.setText("Look your not online");           
}
Share:
29,484
Fahad
Author by

Fahad

Updated on August 29, 2020

Comments

  • Fahad
    Fahad over 3 years

    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();"

  • remi
    remi about 10 years
    Can you give explanations about your code? Why do you set up those request properties? Is this a suitable way to check internet connectivity for very slow/weak connections, that minimize the data transfer for checking the connection availability?
  • tony9099
    tony9099 about 10 years
    @remi. it should work fine. can't see a reason not to. havent tested it on very slow connections tho.
  • Eren Yilmaz
    Eren Yilmaz over 8 years
    It works, but there is a risk of hanging on the DNS request in this solution. The device will try to resolve the web address, and may not reach the DNS server itself.
  • TheLearner
    TheLearner over 6 years
    what is "/system/bin/ping -c 1 8.8.8.8"?
  • Admin
    Admin about 6 years
    return code can be simplified to: return netInfo != null && netInfo.isConnected();