Network Monitoring in Xamarin Forms

Introduction

This article demonstrates how to get the continues  network information using “Xamarin forms” application.

Overview of “Xam.Plugin.Connectivity”

This Connectivity Plugin provides to get Mobile Network Information like, IsConnected, Bandwidth, Network Connection Changes. Etc. If we are developing Xamarin Forms Application, at the time we need to write Native Code to help the Dependency Services to collect all the information’s. But now, without native code we will get all information with the help of Connectivity Plugin.

Here the Steps discussed, Let’s start!

Step 01: Open Visual Studio->New Project->Templates->Visual C#->Cross Platform-> Mobile App(Xamarin.Forms). Now, give the Project Name and Project Location.

Step 02: Next, open a new window. Here, select Template->Blank, Platform=>Android, iOS and finally Code Sharing Strategy ->.NET Standard

Step 03: NuGet Packages Installation, Follow below step:

Package Name:“Xam.Plugin.Connectivity”

Package Installation Ways:

Package Console Manager: PM> Install-Package Xam.Plugin.Connectivity

NuGet Manger: Select Solution -> Manage NuGet Packages for Solutions. In popup window, you need to search “Xam.Plugin.Connectivity” followed by installing “Xam.Plugin.Connectivity

 

Step 04 :Open Solution Explorer->Project Name (.Net Standard)-> MainPage.xaml then click to open XAML Code .

Here is small example “How to create a Design”.

XAML Code:

<StackLayout>
       <ContentView x:Name="ConnectivityPopup" IsVisible="False" BackgroundColor="Transparent"
                   HorizontalOptions="FillAndExpand" VerticalOptions="CenterAndExpand" HeightRequest="40">
       <StackLayout x:Name="StackLayoutConnectyion" IsVisible="True" HorizontalOptions="FillAndExpand"
                   VerticalOptions="FillAndExpand">
                   <Label x:Name="TxtNetworkConnection" Margin="20,0,20,0" FontSize="Medium"
                         HorizontalOptions="StartAndExpand" VerticalOptions="CenterAndExpand"
                         FontFamily="LatoRegular" TextColor="White"></Label>
                </StackLayout>
       </ContentView>
</StackLayout>

 

Step 05: Now, we need to create a Network Changes logic, so that we can create one new class.

Go to Solution Explorer->Project Name (.Net Standard) and right click to Add. Open a new Dialog box and select the Class with any name such as InternetConnectivityCheck.cs. And Click “Add”.

Step 06: Next, Open Solution Explorer->Project Name (PCL)-> InternetConnectivityCheck.cs then click to open cs code to create new “Network Listener” method.

Name Space:

using Plugin.Connectivity;
using Plugin.Connectivity.Abstractions;

 

C# Code:

 

public static void SetupConnectionListeners()
       {
           try
           {
              //Listener Creation
               CrossConnectivity.Current.ConnectivityChanged += CurrentOnConnectivityChanged;
               CrossConnectivity.Current.ConnectivityTypeChanged += CurrentOnConnectivityTypeChanged;
           }
           catch (Exception ex)
           {
           }
       }

//Event Changes Method (CurrentOnConnectivityChanged)

public static void CurrentOnConnectivityChanged(object sender, ConnectivityChangedEventArgs connectivityChangedEventArgs)
       {
           try
           {
               if (connectivityChangedEventArgs.IsConnected)
               {
                   ConnectionRestored();
                   return;
               }
           }
           catch (Exception ex)
           {
           }
       }

//Event Changes Method (CurrentOnConnectivityTypeChanged)

public static void CurrentOnConnectivityTypeChanged(object sender, ConnectivityTypeChangedEventArgs connectivityTypeChangedEventArgs)

       {
           try
           {
               if (!connectivityTypeChangedEventArgs.IsConnected)
               {
                    NoNetwork();
                   return;
               }
               else
               {
                   ConnectionRestored();
                   return;
               }
           }
           catch (Exception ex)
           {
           }
       }

 

      public static void ConnectionRestored()
       {
           try
           {
               // Args Pass MainPage.XAML
               MessagingCenter.Send<string, string>("ConnectivityCheck", "Connectivity", "INTERNET CONNECTION RESTORED");
           }
           catch (Exception ex)
           {
           }
       }


       public static void NoNetwork()
       {
           try
           {
               // Args Pass MainPage.XAML
               MessagingCenter.Send<string, string>("ConnectivityCheck", "Connectivity", "NO INTERNET CONNECTION");
           }
           catch (Exception ex)
           {
           }
       }

 

Step 07: Open Solution Explorer->Project Name (PCL)-> MainPage.xaml cs -> open cs code to create “Message Centre Subscribe” method.

C# Code:

      MessagingCenter.Subscribe<string, string>("ConnectivityCheck", "Connectivity", (sender, arg) =>
 {
 if (arg == "NO INTERNET CONNECTION")
 {
 TxtNetworkConnection.Text = "INTERNET DISCONNECTED";
 StackLayoutConnectyion.BackgroundColor = Color.Red;
 ConnectivityPopup.IsVisible = true;
 }
 else
 {
 TxtNetworkConnection.Text = "INTERNET CONNECTED";
 StackLayoutConnectyion.BackgroundColor = Color.Green;
 ConnectivityPopup.IsVisible = true;
 }
 });

 

Step 08: After Creating “Subscribe method” we need to Initiate the SetupConnectionListeners(). So, Open Solution Explorer->Project Name (PCL)-> App.xaml cs then click to open cs code then put the following code.

C# Code:

   InternetConnectivityCheck.SetupConnectionListeners();

Step 09: Next go to Solution Explorer-> Android Project Name->AndroidManifest.xml and open xml code to give the Permission for Network.

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

<uses-permission android:name="android.permission.INTERNET" />

 

Step 10: Finally set up Default Running Platform [Android /iOS/UWP].

//Output

iOS:

Android:

Download Source Here…

Finally , we are successfully created “continues  network information using Xamarin Forms”.

 

Leave a Comment

Your email address will not be published. Required fields are marked *