Check if internet is available

4 votes · 4 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 ·
copy
· 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

4 Comments

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)).
    getActiveNetworkInfo();

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.

To check for internet connectivity, do you think that a better idea will be to try a ping to any server like www.google.com ?

The reason why I said that is because for this scenario:

When you try to run this code, it checks if the user has a valid connection or not and it doesn't check if the proper internet connection is established. I have tried this similar code before and this checks if the user has the network connection available.

After some research, I found this code snippet which will try to ping to any website e.g. www.google.com and if the response is valid, you can move on from there.

Here's the code snippet :

/**
 *Check internet connectivity by ping
 */
public Boolean isOnline() {
    try {
        p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
        int returnVal = p1.waitFor();
        boolean reachable = (returnVal == 0);
        if (reachable) {

            System.out.println("Internet access");
            return reachable;
        } else {

            System.out.println("No Internet access");
        }

    } catch (Exception e) {

        e.printStackTrace();
    } finally {
        p1.destroy();
    }
    return false;
}
Reply · Sept. 29, 2014, 12:09 p.m.

p1 is the Process and i.e.

Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");

Reply · Sept. 29, 2014, 12:11 p.m.