0

I am trying to detect if there are any active internet connections (WIFI or MOBILE INTERNET). The code is as follows:

private boolean haveNetwork() {
        ConnectivityManager connMgr =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        boolean flag=false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            for (Network network : connMgr.getAllNetworks()) {
                NetworkInfo networkInfo = connMgr.getNetworkInfo(network);
                if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                    flag=true;
                    break;
                } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                    flag=true;
                    break;
                }
            }
        }
        Log.d("flag", String.valueOf(flag)); //returns true even if there's no internet connection
        return flag;
    }

As the title says, my connection status always remains to be true, even if there is no internet connection

2 Answers2

0

What you have currently will only tell you if there is either a mobile or Wi-Fi network tracked by ConnectivityManager, not whether you are connected to it or not.

Since you appear to be doing this synchronously, you want to use these two methods:

You can use this if you want to call ConnectivityManager synchronously by replacing your for loop.

Network activeNetwork = connMgr.getActiveNetwork();
if (null == activeNetwork) {
    return false;
}
NetworkCapabilities nc = connMgr.getNetworkCapabilities(activeNetwork);
return nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) 
    && nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
Always Learning
  • 2,623
  • 3
  • 20
  • 39
0

Use NetworkCapabilities as NetworkInfo is deprecated and check the getLinkDownstreamBandwidthKbps() is greater then 1kbps for 1g 32 kbps for at least 2g speed

RusJaI
  • 666
  • 1
  • 7
  • 28