'Using Context.CONNECTIVITY_SERVICE to check for internet connection

I am using this code to check for the internet connection:

private boolean checkInternetConnection() {
    ConnectivityManager cm = (ConnectivityManager)
                              getSystemService(Context.CONNECTIVITY_SERVICE);
    // test for connection
    if (cm.getActiveNetworkInfo() != null
            && cm.getActiveNetworkInfo().isAvailable()
            && cm.getActiveNetworkInfo().isConnected()) {
        return true;
    } else {
        return false;
    }
}

but even when I turn off the wifi it still returns true.

Tried both on emulator and device with same result?
What is wrong ?



Solution 1:[1]

This simple code works in my case:

public boolean netConnect(Context ctx)
{
    ConnectivityManager cm;
    NetworkInfo info = null;
    try
    {
        cm = (ConnectivityManager) 
              ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        info = cm.getActiveNetworkInfo();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    if (info != null)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Also this one..

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

Solution 2:[2]

You can use following:

    public boolean isNetworkAvailable(Context contextValue) {
    Context context = contextValue;
    ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivity != null) {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
    }

    return false;

}

Solution 3:[3]

Try this....

if((connMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED) ||  (connMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED))                   
{
   return true;
}else
{
   return false;
}

Solution 4:[4]

You can check for both WIFI and internet as follows:

private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;

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

NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
    if (ni.getTypeName().equalsIgnoreCase("WIFI"))
        if (ni.isConnected())
            haveConnectedWifi = true;
    if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
        if (ni.isConnected())
            haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}

Obviously, It could easily be modified to check for individual specific connection types, e.g., if your app needs the potentially higher speeds of Wi-fi to work correctly etc.

Solution 5:[5]

Here's a Kotlin implementation where you get to breakdown which transport your device is connect to the network.

Interesting part would be that you can use <ConnectivityManager> to get from system service without casting it, makes things cleaner.

And, one thing people failed to mention is that connectivityManager?.activeNetwork is only available for Android Marshmallow and above.

For device lower than that, we can resort to connectivityManager?.activeNetworkInfo and activeNetworkInfo.isConnected, even though they are deprecated.

val connectivityManager = context.getSystemService<ConnectivityManager>()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    val activeNetwork = connectivityManager?.activeNetwork ?: return false
    val networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false

    return when {
        networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
        networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
        networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> true
        networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
        networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) -> true
        else -> false
    }
} else {
    val activeNetworkInfo = connectivityManager?.activeNetworkInfo ?: return false
    return activeNetworkInfo.isConnected
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mr_and_Mrs_D
Solution 2
Solution 3 android developer
Solution 4 Frankline
Solution 5 Morgan Koh