0

I am developing an app in Xamarin.Android using Mvvmcross6. To check the network state, I am currently using the following code:

Is this approach correct? Has anything newly came up in Mvvmcross6?

public void NetworkStatus()
    {
        _state = NetworkState.Unknown;

        //Retrieve the connectivity manager service
        var connectivityManager = (ConnectivityManager)Application.Context.GetSystemService(Context.ConnectivityService);

        //Check if the network is connected or connecting.
        //This means that it will be available,
        //or become available in a few seconds. 
        var activeNetworkInfo = connectivityManager.ActiveNetworkInfo;

        if(activeNetworkInfo.IsConnectedOrConnecting)
        {
            _state = activeNetworkInfo.Type == ConnectivityType.Wifi ? NetworkState.ConnectedWifi : NetworkState.ConnectedData;
        }
        else
        {
            _state = NetworkState.Disconnected;
        }
    }
Maria
  • 77
  • 5
  • 13
  • Mvvmcross, in general, has nothing to do with the network state of your mobile device because all it actually is, is an MVVM framework the right question would be if there is another way of doing it in android and my experience tells me checking the network state would be the best way of doing it and also logically the only way of doing and yes this code is the right way of doing this still. – FreakyAli Aug 09 '18 at 12:45
  • @G.hakim I do agree with you. I could see references of Mvvmcross connectivity plugin in older posts https://stackoverflow.com/questions/33343015/check-whether-internet-is-on-or-off-in-xamarin-android – Maria Aug 09 '18 at 13:51
  • Yeah anyway you have your answer now so good luck – FreakyAli Aug 10 '18 at 06:33

1 Answers1

2

MvvmCross has a Network Plugin but it won't do exactly what you're looking for. The MvvmCross Network Plugin provides cross platform implementations for making Web API calls. The Network Plugin also has a reachability service which is useful to see if you can successfully ping a host.

There is also a Xamarin Connectivity Plugin available by James Montemagno. This plugin more closely matches what you are trying to accomplish. It has API to determine if you are connected, and what types of connections are available.

Finally, there is Xamarin Essentials which is pretty close to the Xamarin Connectivity Plugin. Xamarin Essentials is like a kitchen sink plugin library with cross platform support for connectivity and much more. This is the newest of the 3 libraries and is most up to date with high quality documentation.

If you're only concerned with Android then your code is fine.

Trevor Balcom
  • 3,766
  • 2
  • 32
  • 51