connectivitymanager.getActiveNetworkInfo() returning true when Internet is off (Android)?

StackOverflow https://stackoverflow.com/questions/17287178

  •  01-06-2022
  •  | 
  •  

Question

This is the code I am using to determine if the phone is connected to the Internet:

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

On an emulator, this is returning true even when I turn my computer's Wi-Fi off. I see a 3G sign on the topmost bar of the emulator, even when the computer is off the Internet. Is there something wrong with my code, or is this an emulator problem?

Était-ce utile?

La solution

You should call isConnected instead of isConnectedOrConnecting if you want to determine whether the device is connected at the time of call to isOnline.

Generally, there are many problems/bugs with hardware-features APIs on the emulator, this might be one of them. Your code is fine.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top