3

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 ?

Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
Navdroid
  • 4,453
  • 7
  • 29
  • 47

5 Answers5

7

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;
}
Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
user370305
  • 108,599
  • 23
  • 164
  • 151
  • 1
    The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none if the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available. – user370305 Jan 25 '12 at 11:56
  • Does this require any special permissions like ACCESS_WIFI_STATE? – Bill Mote Feb 05 '16 at 16:23
  • 1
    getActiveNetworkInfo: "This method was deprecated in API level 29." NetworkInfo: "This class was deprecated in API level 29. Callers should instead use the ConnectivityManager.NetworkCallback API to learn about connectivity changes...". Try my answer on: https://stackoverflow.com/a/64977886/1741997 – cesargastonec Nov 24 '20 at 15:15
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;

}
Vicky Kapadia
  • 6,025
  • 2
  • 24
  • 30
1

Try this....

if((connMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED) ||  (connMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED))                   
{
   return true;
}else
{
   return false;
}
android developer
  • 1,253
  • 2
  • 13
  • 43
1

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.

Frankline
  • 40,277
  • 8
  • 44
  • 75
0

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
}
Morgan Koh
  • 2,297
  • 24
  • 24