How to programmatically check availibilty of internet connection in Android?
Asked Answered
L

8

21

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

Loco answered 25/12, 2010 at 16:48 Comment(0)
M
27

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.

Madriene answered 25/12, 2010 at 17:23 Comment(1)
return code can be simplified to: return netInfo != null && netInfo.isConnected();Schoolhouse
C
12

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
}
Criterion answered 25/2, 2013 at 21:44 Comment(3)
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?Resh
@remi. it should work fine. can't see a reason not to. havent tested it on very slow connections tho.Criterion
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.Ferret
D
10

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://mcmap.net/q/11339/-how-to-check-internet-access-on-android-inetaddress-never-times-out

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?)

Drin answered 15/10, 2015 at 12:0 Comment(0)
R
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"

Related answered 1/2, 2016 at 12:15 Comment(0)
N
2

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");           
}
Norway answered 25/12, 2010 at 17:6 Comment(0)
C
1

From my OLD Answer here

Just try this

I have applied the solution provided by @Levit and created function that will not call the extra Http Request.

It will solve the error Unable to Resolve Host

public static boolean isInternetAvailable(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork == null) return false;

    switch (activeNetwork.getType()) {
        case ConnectivityManager.TYPE_WIFI:
            if ((activeNetwork.getState() == NetworkInfo.State.CONNECTED ||
                    activeNetwork.getState() == NetworkInfo.State.CONNECTING) &&
                    isInternet())
                return true;
            break;
        case ConnectivityManager.TYPE_MOBILE:
            if ((activeNetwork.getState() == NetworkInfo.State.CONNECTED ||
                    activeNetwork.getState() == NetworkInfo.State.CONNECTING) &&
                    isInternet())
                return true;
            break;
        default:
            return false;
    }
    return false;
}

private static boolean isInternet() {

    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int exitValue = ipProcess.waitFor();
        Debug.i(exitValue + "");
        return (exitValue == 0);
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }

    return false;
}

Now call it like,

if (!isInternetAvailable(getActivity())) {
     //Show message
} else {
     //Perfoem the api request
}
Chapatti answered 10/1, 2017 at 18:50 Comment(1)
what is "/system/bin/ping -c 1 8.8.8.8"?Spirited
I
0

Because you are connected to a network does not guaruntee that you have internet, I have gone to just making my calls to the internet inside of a try catch block. Then catch the UnknownHostException to handle no internet.

Introduction answered 25/12, 2010 at 22:44 Comment(0)
G
0

this code must be run in background thread

fun hasActiveInternetConnection(): Boolean {
    return try {
        val ipAddr: InetAddress = InetAddress.getByName("google.com")
        !ipAddr.equals("")
    } catch (e: java.lang.Exception) {
        false
    }
}
Gambrinus answered 28/8, 2020 at 12:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.