Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Xamarin

Xamarin forms: Check network connectivity in iOS and Android

3.85/5 (7 votes)
28 Jan 2015CPOL 73.3K   1.3K  
Network connectivity check using Xamarin forms in iOS and Android

Introduction

This article explains how to check network connectivity in iOS and Android. 

I had to do the same in one of my project using Xamarin forms, but I could not find any sample that does the same. There are samples in Xamarin that do the same natively. But I wanted to achive the same using forms. 

I have taken code from each platform and used dependency services to check connectivty in the Xamarin forms pages. Please find the attached for sample code.

Background

Mobile development using Xamarin forms.

Using the code

In the portable class library add a class file called INetworkConnection as shown below:

C#
    public interface INetworkConnection
    {
        bool IsConnected { get; }
        void CheckNetworkConnection();
    }

 

and go the Android project and add code as show below, here adding assembly is important and its class name in it.

C#
[assembly: Dependency(typeof(NetworkConnection))]
namespace FormsNetworkConnectivity.Droid
{

    public class NetworkConnection : INetworkConnection
    {
        public bool IsConnected { get; set; }
        public void CheckNetworkConnection()
        {
            var connectivityManager = (ConnectivityManager)Application.Context.GetSystemService(Context.ConnectivityService);
            var activeNetworkInfo = connectivityManager.ActiveNetworkInfo;
            if (activeNetworkInfo != null && activeNetworkInfo.IsConnectedOrConnecting)
            {
                IsConnected = true;
            }
            else
            {
                IsConnected = false;
            }
        }
    }
}

 

and on iOS project add below code and remember its assebly attribute

C#
[assembly: Dependency(typeof(NetworkConnection))]
namespace FormsNetworkConnectivity.iOS.Network
{
    public class NetworkConnection : INetworkConnection
    {

/*        public NetworkConnection()
        {
            InternetConnectionStatus();
        }*/
        public bool IsConnected { get; set; }
        public void CheckNetworkConnection()
        {
            InternetConnectionStatus();
        }

        private void UpdateNetworkStatus()
        {
            if (InternetConnectionStatus())
            {
                IsConnected = true;
            }
            else if (LocalWifiConnectionStatus())
            {
                IsConnected = true;
            }
            else
            {
                IsConnected = false;
            }
        }

        private event EventHandler ReachabilityChanged;
        private void OnChange(NetworkReachabilityFlags flags)
        {
            var h = ReachabilityChanged;
            if (h != null)
                h(null, EventArgs.Empty);
        }

        private NetworkReachability defaultRouteReachability;
        private bool IsNetworkAvailable(out NetworkReachabilityFlags flags)
        {
            if (defaultRouteReachability == null)
            {
                defaultRouteReachability = new NetworkReachability(new IPAddress(0));
                defaultRouteReachability.SetCallback(OnChange);
                defaultRouteReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault);
            }
            if (!defaultRouteReachability.TryGetFlags(out flags))
                return false;
            return IsReachableWithoutRequiringConnection(flags);
        }

        private NetworkReachability adHocWiFiNetworkReachability;
        private bool IsAdHocWiFiNetworkAvailable(out NetworkReachabilityFlags flags)
        {
            if (adHocWiFiNetworkReachability == null)
            {
                adHocWiFiNetworkReachability = new NetworkReachability(new IPAddress(new byte[] { 169, 254, 0, 0 }));
                adHocWiFiNetworkReachability.SetCallback(OnChange);
                adHocWiFiNetworkReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault);
            }

            if (!adHocWiFiNetworkReachability.TryGetFlags(out flags))
                return false;

            return IsReachableWithoutRequiringConnection(flags);
        }

        public static bool IsReachableWithoutRequiringConnection(NetworkReachabilityFlags flags)
        {
            // Is it reachable with the current network configuration?
            bool isReachable = (flags & NetworkReachabilityFlags.Reachable) != 0;

            // Do we need a connection to reach it?
            bool noConnectionRequired = (flags & NetworkReachabilityFlags.ConnectionRequired) == 0;

            // Since the network stack will automatically try to get the WAN up,
            // probe that
            if ((flags & NetworkReachabilityFlags.IsWWAN) != 0)
                noConnectionRequired = true;

            return isReachable && noConnectionRequired;
        }

        private bool InternetConnectionStatus()
        {
            NetworkReachabilityFlags flags;
            bool defaultNetworkAvailable = IsNetworkAvailable(out flags);
            if (defaultNetworkAvailable && ((flags & NetworkReachabilityFlags.IsDirect) != 0))
            {
                return false;
            }
            else if ((flags & NetworkReachabilityFlags.IsWWAN) != 0)
            {
                return true;
            }
            else if (flags == 0)
            {
                return false;
            }

            return true;
        }

        private bool LocalWifiConnectionStatus()
        {
            NetworkReachabilityFlags flags;
            if (IsAdHocWiFiNetworkAvailable(out flags))
            {
                if ((flags & NetworkReachabilityFlags.IsDirect) != 0)
                    return true;
            }
            return false;
        }
    }
}

Now go the page you want to check connectivity and do similar as below

C#
var networkConnection = DependencyService.Get<INetworkConnection>();
            networkConnection.CheckNetworkConnection();
            var networkStatus = networkConnection.IsConnected ? "Connected" : "Not Connected";

            var speak = new Button
            {
                Text = "Click to check Network connectivity",
                VerticalOptions = LayoutOptions.CenterAndExpand,
                HorizontalOptions = LayoutOptions.CenterAndExpand,
            };
            

            speak.Clicked += (sender, e) =>
            {
                speak.Text = DependencyService.Get<INetworkConnection>().IsConnected ? "You are Connected" : "You are Not Connected";
            };

            Content = speak;

 

Thats you need to do to get Network connectivity using Xamarin forms from iOS and Android

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)