Check Internet Connectivity

Frequently used code samples and tutorials
vivekkalady
Site Admin
Posts: 35
Joined: Tue Nov 18, 2014 2:39 pm

Check Internet Connectivity

Postby vivekkalady » Wed Nov 19, 2014 4:03 pm

How to check for internet connectivity before requesting

Code: Select all

public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}


Also add the following permission to the AndroidManifest.xml:

Code: Select all

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


One other small point, if you absolutely need a network connection at the given point in time, then it might be better to use

Code: Select all

netInfo.isConnected()
 rather than
netInfo.isConnectedOrConnecting()

I guess this is up to the indivudal use-case however.



For checking all the NetworkInfo you can use a better solution like this

Code: Select all

public boolean isConnected() {
    boolean connected = false;

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

    if (cm != null) {
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();

        for (NetworkInfo ni : netInfo) {
            if ((ni.getTypeName().equalsIgnoreCase("WIFI")
                    || ni.getTypeName().equalsIgnoreCase("MOBILE"))
                    && ni.isConnected() && ni.isAvailable()) {
                connected = true;
            }

        }
    }

    return connected;
}

Return to “Tutorials & Examples”

Who is online

Users browsing this forum: No registered users and 1 guest

cron