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. ConnectivityManager cm = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
  15. NetworkInfo activeConnection = cm.ActiveNetworkInfo;
  16. isNetworkActive = (activeConnection != null) && activeConnection.IsConnected;
  17. return isNetworkActive;
  18. }
  19. }

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. public bool isNetworkReachable()
  7. {
  8. bool hasInternet = true;
  9. NetworkStatus internetStatus = Reachability.InternetConnectionStatus();
  10. if (internetStatus == NetworkStatus.NotReachable)
  11. {
  12. hasInternet = false;
  13. }
  14. return hasInternet;
  15. }
  16. }

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

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. public void clickedButton(Object sender, EventArgs e)
  8. {
  9. bool internetActive = DependencyService.Get<IDeviceState>().isNetworkReachable();
  10. this.DisplayAlert("Device Network", internetActive.ToString(), "OK");
  11. }
  12. }

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).