In this post, I will be explaining how to check the internet connection in a device using Dependency Service in Xamarin.Forms.
Prerequisites
- 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.
Step 2
If you select “Project” in the above context menu, the following window will open.
In the above image,
- Select “Cross-Platform” option from the left pane.
- Choose “Mobile App (Xamarin.Forms)” option for creating Xamarin.Forms application.
- Choose the location on the disk where you want to store your application on the hard disk.
- 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.
In the above image.
- Choose what type of application you are going to develop. In my case, I am choosing “Blank App”.
- In the second step, check the checkboxes before platform names (Android, iOS, Windows(UWP)) for which you will be developing an application.
- 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.
Step 5
Right click on “CheckInternet” project and select Add=>New Item like below.
Step 6
After clicking “New Item” in the above step, the following window will open.
From the above image,
- Choose “Code” from the left lane.
- Select “Interface” among all the options listed.
- 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.
- public interface IDeviceState
- {
- bool isNetworkReachable();
- }
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.
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.CheckInternet" android:installLocation="auto">
- <uses-sdk android:minSdkVersion="19" />
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
- <application android:label="CheckInternet.Android"></application>
- </manifest>
- public class DeviceState : IDeviceState
- {
- public bool isNetworkReachable()
- {
- bool isNetworkActive;
- Context context = Forms.Context;
-
- ConnectivityManager cm = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
- NetworkInfo activeConnection = cm.ActiveNetworkInfo;
- isNetworkActive = (activeConnection != null) && activeConnection.IsConnected;
-
- return isNetworkActive;
- }
- }
Finally, add [assembly: Dependency(typeof(**********************))] on the top of the namespace statement.
Step 8
Implementation of interface in iOS project is as below,
- public class DeviceState : IDeviceState
- {
- public DeviceState()
- {
- }
-
- public bool isNetworkReachable()
- {
- bool hasInternet = true;
- NetworkStatus internetStatus = Reachability.InternetConnectionStatus();
-
- if (internetStatus == NetworkStatus.NotReachable)
- {
- hasInternet = false;
-
- }
- return hasInternet;
- }
- }
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.
Step 9
Inside of PCL/NET Standard project, in MainPage.xaml, add the following code between <ContentPage> </ContentPage> tags.
- <Button Text="Check Network Reaachability"
- VerticalOptions="Center"
- HorizontalOptions="Center"
- Clicked="clickedButton"/>
In the code behind MainPage, that is, MainPage.xaml.cs, please add the following code.
- public partial class MainPage : ContentPage
- {
- public MainPage()
- {
- InitializeComponent();
- }
-
- public void clickedButton(Object sender, EventArgs e)
- {
- bool internetActive = DependencyService.Get<IDeviceState>().isNetworkReachable();
- this.DisplayAlert("Device Network", internetActive.ToString(), "OK");
- }
-
- }
Now, run your application. The output will be as given below.
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).