Network status always returns true for isConnected () and isConnectedOrConnecting ()

My application needs to know if it has internet access or not. I tried to follow the best practice on StackOverflow question ... However, the following method always returns true:

public static boolean isOnline(Context context) {

    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();

}

      

A similar question was asked earlier Network status is always true for Android. How? However, the proposed solution uses legacy methods and shouldn't be a solution anyway, I suppose.

I am running code on an emulator that runs on my development machine (my laptop) and I test my code using a few conditions:

  • disable WIFI on laptop (and without cable)
  • enable airplane mode on the laptop.
  • use adb shell svc wifi enable / disable

    for direct work with the emulator.

No matter what I do, it always returns true and gives me a timeout when I actually try to connect to the www resource (so there is no magic internet connection):

String searchResultsStr = IOUtils.toString(url.openStream());

      

Help someone?

+3


source to share





All Articles