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

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

  •  01-06-2022
  •  | 
  •  

문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top