How To Check Internet Connection In Device Using Dependency Service Xamarin.Forms

In this post, I will be explaining how to check the internet connection in a device using Dependency Service in Xamarin.Forms.

Prerequisites

  1. Visual Studio with Xamarin templates installed in either Windows machine or Mac machine.

In my case, I am using a Windows machine to demonstrate this post.

Step 1

Create a new project using Visual Studio, as below shown.

Xamarin

 

Step 2

If you select “Project” in the above context menu, the following window will open.

Xamarin

 

In the above image,

  1. Select “Cross-Platform” option from the left pane.
  2. Choose “Mobile App (Xamarin.Forms)” option for creating Xamarin.Forms application.
  3. Choose the location on the disk where you want to store your application on the hard disk.
  4. Give some name to your project which is relevant to your task. In my case, I’m giving it the name “CheckInternet”.

Step 3

After completing the actions given in step 2, click “OK” button. Then, one more window will open like below.

Xamarin

In the above image.

  1. Choose what type of application you are going to develop. In my case, I am choosing “Blank App”.
  2. In the second step, check the checkboxes before platform names (Android, iOS, Windows(UWP)) for which you will  be developing an application.
  3. In the third step, choose the code sharing method based on your requirements and future scope of an application.

Step 4

Click “OK” after doing the action in step 3. Then, it will create a project. The following image depicts how the project structure will be.

Xamarin

 

Step 5

Right click on “CheckInternet” project and select Add=>New Item like below.

Xamarin

Step 6

After clicking “New Item”  in the above step, the following window will open.

Xamarin

 

From the above image,

  1. Choose “Code” from the left lane.
  2. Select “Interface” among all the options listed.
  3. Enter some name for the interface. In my case, I’m giving “IDeviceState”.

Step 7

Click “Add” button from the above window, then interface will be added to the “CheckInternet” project. Replace the created interface with the following code.

  1. public interface IDeviceState  
  2.     {  
  3.         bool isNetworkReachable();  
  4.     }  

Step 8

Since we are using Dependency Service, we have to  Implement the interface in both Android and iOS projects. For the first, I am going to be implementing the interface in Android project as below.

Before proceeding in Android project, you should have enabled INTERNET permission and ACCESS_NETWORK_STATE permission from Manifest.xml file like below.

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.CheckInternet" android:installLocation="auto">  
  3.     <uses-sdk android:minSdkVersion="19" />  
  4.     <uses-permission android:name="android.permission.INTERNET" />  
  5. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
  6.     <application android:label="CheckInternet.Android"></application>  
  7. </manifest>  
  8. public class DeviceState : IDeviceState  
  9.     {  
  10.         public bool isNetworkReachable()  
  11.         {  
  12.             bool isNetworkActive;// = false;  
  13.             Context context = Forms.Context; //get the current application context  
  14.   
  15.             ConnectivityManager cm = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);  
  16.             NetworkInfo activeConnection = cm.ActiveNetworkInfo;  
  17.             isNetworkActive = (activeConnection != null) && activeConnection.IsConnected;  
  18.   
  19.             return isNetworkActive;  
  20.         }  
  21.     }  

Finally, add [assembly: Dependency(typeof(**********************))] on the top of the namespace statement.

Step 8

Implementation of interface in iOS project is as below,

  1. public class DeviceState : IDeviceState  
  2.     {  
  3.         public DeviceState()  
  4.         {  
  5.         }  
  6.   
  7.         public bool isNetworkReachable()  
  8.         {  
  9.             bool hasInternet = true;  
  10.             NetworkStatus internetStatus = Reachability.InternetConnectionStatus();  
  11.   
  12.             if (internetStatus == NetworkStatus.NotReachable)  
  13.             {  
  14.                 hasInternet = false;  
  15.   
  16.             }  
  17.             return hasInternet;  
  18.         }  
  19.     }  

We have to add [assembly: Dependency(typeof(**********************))] on top of the namespace statement.

Other than this, in iOS, we have to add one more class,  “Reachability”. Actually, the Reachability class has logic to check for an internet connection.

Here, I’m adding reachability class and one enum as below.

  1. public enum NetworkStatus  
  2.     {  
  3.         NotReachable,  
  4.         ReachableViaCarrierDataNetwork,  
  5.         ReachableViaWiFiNetwork  
  6.     }  
  7.   
  8.     public static class Reachability  
  9.     {  
  10.         public static string HostName = "www.google.com";  
  11.   
  12.         public static bool IsReachableWithoutRequiringConnection(NetworkReachabilityFlags flags)  
  13.         {  
  14.             // Is it reachable with the current network configuration?  
  15.             bool isReachable = (flags & NetworkReachabilityFlags.Reachable) != 0;  
  16.   
  17.             // Do we need a connection to reach it?  
  18.             bool noConnectionRequired = (flags & NetworkReachabilityFlags.ConnectionRequired) == 0  
  19.                 || (flags & NetworkReachabilityFlags.IsWWAN) != 0;  
  20.   
  21.             return isReachable && noConnectionRequired;  
  22.         }  
  23.   
  24.         // Is the host reachable with the current network configuration  
  25.         public static bool IsHostReachable(string host)  
  26.         {  
  27.             if (string.IsNullOrEmpty(host))  
  28.                 return false;  
  29.   
  30.             using (var r = new NetworkReachability(host))  
  31.             {  
  32.                 NetworkReachabilityFlags flags;  
  33.   
  34.                 if (r.TryGetFlags(out flags))  
  35.                     return IsReachableWithoutRequiringConnection(flags);  
  36.             }  
  37.             return false;  
  38.         }  
  39.   
  40.         //  
  41.         // Raised every time there is an interesting reachable event,  
  42.         // we do not even pass the info as to what changed, and  
  43.         // we lump all three status we probe into one  
  44.         //  
  45.         public static event EventHandler ReachabilityChanged;  
  46.   
  47.         static void OnChange(NetworkReachabilityFlags flags)  
  48.         {  
  49.             var h = ReachabilityChanged;  
  50.             if (h != null)  
  51.                 h(null, EventArgs.Empty);  
  52.         }  
  53.   
  54.         //  
  55.         // Returns true if it is possible to reach the AdHoc WiFi network  
  56.         // and optionally provides extra network reachability flags as the  
  57.         // out parameter  
  58.         //  
  59.         static NetworkReachability adHocWiFiNetworkReachability;  
  60.   
  61.         public static bool IsAdHocWiFiNetworkAvailable(out NetworkReachabilityFlags flags)  
  62.         {  
  63.             if (adHocWiFiNetworkReachability == null)  
  64.             {  
  65.                 adHocWiFiNetworkReachability = new NetworkReachability(new IPAddress(new byte[] { 169, 254, 0, 0 }));  
  66.                 adHocWiFiNetworkReachability.SetNotification(OnChange);  
  67.                 adHocWiFiNetworkReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault);  
  68.             }  
  69.   
  70.             return adHocWiFiNetworkReachability.TryGetFlags(out flags) && IsReachableWithoutRequiringConnection(flags);  
  71.         }  
  72.   
  73.         static NetworkReachability defaultRouteReachability;  
  74.   
  75.         static bool IsNetworkAvailable(out NetworkReachabilityFlags flags)  
  76.         {  
  77.             if (defaultRouteReachability == null)  
  78.             {  
  79.                 defaultRouteReachability = new NetworkReachability(new IPAddress(0));  
  80.                 defaultRouteReachability.SetNotification(OnChange);  
  81.                 defaultRouteReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault);  
  82.             }  
  83.             return defaultRouteReachability.TryGetFlags(out flags) && IsReachableWithoutRequiringConnection(flags);  
  84.         }  
  85.   
  86.         static NetworkReachability remoteHostReachability;  
  87.   
  88.         public static NetworkStatus RemoteHostStatus()  
  89.         {  
  90.             NetworkReachabilityFlags flags;  
  91.             bool reachable;  
  92.   
  93.             if (remoteHostReachability == null)  
  94.             {  
  95.                 remoteHostReachability = new NetworkReachability(HostName);  
  96.   
  97.                 // Need to probe before we queue, or we wont get any meaningful values  
  98.                 // this only happens when you create NetworkReachability from a hostname  
  99.                 reachable = remoteHostReachability.TryGetFlags(out flags);  
  100.   
  101.                 remoteHostReachability.SetNotification(OnChange);  
  102.                 remoteHostReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault);  
  103.             }  
  104.             else  
  105.             {  
  106.                 reachable = remoteHostReachability.TryGetFlags(out flags);  
  107.             }  
  108.   
  109.             if (!reachable)  
  110.                 return NetworkStatus.NotReachable;  
  111.   
  112.             if (!IsReachableWithoutRequiringConnection(flags))  
  113.                 return NetworkStatus.NotReachable;  
  114.   
  115.             return (flags & NetworkReachabilityFlags.IsWWAN) != 0 ?  
  116.                 NetworkStatus.ReachableViaCarrierDataNetwork : NetworkStatus.ReachableViaWiFiNetwork;  
  117.         }  
  118.   
  119.         public static NetworkStatus InternetConnectionStatus()  
  120.         {  
  121.             NetworkReachabilityFlags flags;  
  122.             bool defaultNetworkAvailable = IsNetworkAvailable(out flags);  
  123.             if (defaultNetworkAvailable && ((flags & NetworkReachabilityFlags.IsDirect) != 0))  
  124.                 return NetworkStatus.NotReachable;  
  125.             else if ((flags & NetworkReachabilityFlags.IsWWAN) != 0)  
  126.                 return NetworkStatus.ReachableViaCarrierDataNetwork;  
  127.             else if (flags == 0)  
  128.                 return NetworkStatus.NotReachable;  
  129.             return NetworkStatus.ReachableViaWiFiNetwork;  
  130.         }  
  131.   
  132.         public static NetworkStatus LocalWifiConnectionStatus()  
  133.         {  
  134.             NetworkReachabilityFlags flags;  
  135.             if (IsAdHocWiFiNetworkAvailable(out flags))  
  136.                 if ((flags & NetworkReachabilityFlags.IsDirect) != 0)  
  137.                     return NetworkStatus.ReachableViaWiFiNetwork;  
  138.   
  139.             return NetworkStatus.NotReachable;  
  140.         }  
  141.     }  

Step 9

Inside of PCL/NET Standard project, in MainPage.xaml, add the following code between <ContentPage> </ContentPage> tags.

  1. <Button Text="Check Network Reaachability"   
  2.            VerticalOptions="Center"   
  3.            HorizontalOptions="Center"  
  4.            Clicked="clickedButton"/>  

In the code behind MainPage, that is, MainPage.xaml.cs, please add the following code.

  1. public partial class MainPage : ContentPage  
  2.     {  
  3.         public MainPage()  
  4.         {  
  5.             InitializeComponent();  
  6.         }  
  7.   
  8.         public void clickedButton(Object sender, EventArgs e)  
  9.         {  
  10. bool internetActive =     DependencyService.Get<IDeviceState>().isNetworkReachable();  
  11.               this.DisplayAlert("Device Network", internetActive.ToString(), "OK");  
  12.         }  
  13.   
  14.     }  

Now, run your application. The output will be as given below.

Xamarin

Xamarin

Xamarin

If you want the full source, click here.

Thanks for reading the article. Please comment if you have any doubts. I will get back to you with the proper answer(s).


Similar Articles