How To Bring Internet Connectivity To Xamarin.Forms Application

Introduction

This article demonstrates how to bring internet connectivity to Xamarin.Forms.

Let’s start.

Step 1

Open Visual Studio and go to New Project >> Installed >> Visual C# >> Cross-Platform.

Select Cross-Platform app, then give your project a Name and Location.



Step 2

Add the following NuGet Packages to your project.
  • Xam.Plugin.Connectivity
  • Xamarin.Forms
Go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for Solution".



Now, select the following NuGet Package and select your project to install it.

 

Similarly, add the Xamarin.Forms Nuget.



Step 3

Open Solution Explorer >> Project Name >> Mainpage.xaml. Open the Design View of this page.

 

The code is given below.



XAML Code
 
  1. <Button x:Name="Btn" Text="Check Connectivity" Clicked="Btn_Clicked"/>  
  2.           <Label x:Name="Lbl" Text="Status"/>  
  3.           <Label x:Name="Lbl1" Text="Type:/"/>  
Step 4

Open Solution Explorer >> Project Name >> Mainpage.xaml.cs  Open the Design View of this page.

 
 

C# Code
  1. namespace ConnectivityCheck  
  2. {  
  3.     public partial class MainPage : ContentPage  
  4.     {  
  5.         public MainPage()  
  6.         {  
  7.             InitializeComponent();  
  8.         }  
  9.         private void Btn_Clicked(object sender, EventArgs e)  
  10.         {  
  11.             var Status = CrossConnectivity.Current.IsConnected ? "Is Connected" : "Not Connected";  
  12.             Lbl.Text = $"Status :{Status}";  
  13.             Lbl1.Text = $"Type:{CrossConnectivity.Current.ConnectionTypes.ToString() }";  
  14.         }  
  15.     }  
  16. }  
Step 5

Press F5 or Build and Run the application.

OutPut 1

Mobile Data On will result in "Connected" status.

 

Output 2

Mobile Data Off will result in NotConnected status.



Finally, we have successfully created a Xamarin.Forms InternetConnectivity app.


Similar Articles