Click here to Skip to main content
15,868,164 members
Articles / Mobile Apps / Xamarin
Tip/Trick

Xamarin forms: Check network connectivity in iOS and Android

Rate me:
Please Sign up or sign in to vote.
3.85/5 (7 votes)
28 Jan 2015CPOL 70.3K   1.3K   17   17
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)


Written By
Software Developer (Senior)
Australia Australia
I am a, hands-on, Microsoft C# Analyst Programmer using Xamarin, Azure, WPF and MVC as my preferred tools, also as Team Lead and Scrum Master. My experience include in analysis, object oriented design, development and implementation of client, server, web and windows based applications and enterprise mobile apps using latest Microsoft technologies such as MVC, WPF and Xamarin Forms.

I have worked with Microsoft technologies for over 10 years building software for various private sector companies, applying both technical knowledge and managerial expertise.

My preferred technology stack includes C#, Azure, WPF, MVC, Entity Framework, Xamarin and SQL Server and highly prefer working on various design patterns and architectures.

An integral part of my work is to provide my clients with a high standard of understandable technical documentation: I have written few articles listed few page down in this resume, designs, as well as User Guides.

Using Azure for over 1.5 year, migrating application to the cloud, fully managed continuous integration for all environments.

Comments and Discussions

 
QuestionNice one Man Pin
Logesh Palani4-Aug-19 4:49
Logesh Palani4-Aug-19 4:49 
Questionwhat is the advantage of this over "xam.plugin.connectivity"? Pin
jilanisk0917-Jan-19 19:38
jilanisk0917-Jan-19 19:38 
QuestionSeems to be incompatible with latest Xamarin / VS2017 Pin
Member 1176193619-Feb-18 23:27
Member 1176193619-Feb-18 23:27 
Questionnet connectivity Pin
mandarking2-Nov-17 4:03
mandarking2-Nov-17 4:03 
QuestionUWP Pin
3rd Kelly22-May-17 5:30
3rd Kelly22-May-17 5:30 
QuestionIn ios not working Pin
S M Hasan19-Jan-16 10:41
S M Hasan19-Jan-16 10:41 
QuestionNice Artical Pin
lk.934614-Jan-16 22:23
lk.934614-Jan-16 22:23 
QuestionXamarin forms: Check network connectivity in iOS and Android Pin
Member 89499707-Oct-15 2:16
Member 89499707-Oct-15 2:16 
AnswerRe: Xamarin forms: Check network connectivity in iOS and Android Pin
S M Hasan19-Jan-16 10:38
S M Hasan19-Jan-16 10:38 
AnswerRe: Xamarin forms: Check network connectivity in iOS and Android Pin
Miha Svalina10-Aug-17 1:28
Miha Svalina10-Aug-17 1:28 
QuestionCaused by: java.lang.SecurityException: ConnectivityService: Neither user 10061 nor current process has android.permission.ACCESS_NETWORK_STATE. Pin
Member 119583923-Sep-15 19:33
Member 119583923-Sep-15 19:33 
GeneralMy vote of 4 Pin
Franc Morales3-Jun-15 20:05
Franc Morales3-Jun-15 20:05 
GeneralMy vote of 1 Pin
sh_cheah16-May-15 6:35
sh_cheah16-May-15 6:35 
QuestionDownload link is broken Pin
sh_cheah16-May-15 6:29
sh_cheah16-May-15 6:29 
QuestionDownload links not working Pin
LordCornwalis28-Apr-15 8:48
LordCornwalis28-Apr-15 8:48 
Buggreat! Pin
Member 83872057-Feb-15 8:50
Member 83872057-Feb-15 8:50 
GeneralRe: great! Pin
Robert Hellestrae3-Oct-15 9:51
Robert Hellestrae3-Oct-15 9:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.