Forum Xamarin.Android

isOnline is always returning true even if the simulator is not connected to wifi.

In my Xamarin.Android application I need to check if the phone is connected to the network (wifi or mobile data) before making a web service call. I followed the following Xamarin android tutorial: https://developer.xamarin.com/recipes/android/networking/networkinfo/detect_network_connection/

The problem is when I turn off my laptop wifi and run the simulator, isOnline is still returning true. And so is wifiInfo.IsConnected. Here is my code in OnCreate method:

        connectivityManager = (ConnectivityManager)GetSystemService(Context.ConnectivityService);
        NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo;
        isOnline = (activeConnection != null) && activeConnection.IsConnected;

        Log.Debug("DEBUG", "The value of isOnline is: {0}", isOnline);

        NetworkInfo wifiInfo = connectivityManager.GetNetworkInfo(ConnectivityType.Wifi);
        if (wifiInfo.IsConnected)
        {
            Log.Debug("DEBUG", "Wifi connected.");

        }
        else
        {
            Log.Debug("DEBUG", "Wifi disconnected.");

        }

        NetworkInfo mobileInfo = connectivityManager.GetNetworkInfo(ConnectivityType.Mobile);
        if (mobileInfo.IsRoaming && mobileInfo.IsConnected)
        {
            Log.Debug("DEBUG", "Roaming.");

        }
        else
        {
            Log.Debug("DEBUG", "Not roaming.");

        }

Why is IsOnline and wifiInfo.isConnected both returning true even though I turned wifi off?

Best Answer

Answers

  • Thanks it worked

  • I have one more question, if you could help me out it would be great.

    I need to check for network connection constantly. And as soon as the network connection changes I need to be notified. How can I implement that?

Sign In or Register to comment.