Handling the internet connection in any applications is a must if those applications interact with the network and we also must notify the user that he/she is disconnected from the internet. So In this article, I’m going to show you how to check internet connection continuously in Xamarin Forms from a single place.
Let’s Start
In this sample demo I will use Xamarin.Essentials.Connectivity.cs static class for handling internet connection changes.
1 – Install Xamarin.Essentials nuget package.
![Xamarin Essentials](https://learnmobiledevelopment.com/wp-content/uploads/2022/12/XamarinEssentials-1024x563.png)
2 – In Android project
2.1 Initialize Xamarin Essentials in OnCreate() method
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Initializing Xamarin Essentials Xamarin.Essentials.Platform.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); LoadApplication(new App()); }
2.2 Add ACCESS_NETWORK_STATE permission in manifest file
<?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.xfinternetstatussample"> <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="31" /> <application android:label="XFInternetStatusSample.Android" android:theme="@style/MainTheme"></application> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> </manifest>
3 – Create a NetworkConnectivity.cs class for handling network connections
using Xamarin.Essentials; namespace XFInternetStatusSample { public class NetworkConnectivity { private bool IsInternetConnected; #region Constructor public NetworkConnectivity() { // Register for connectivity changes, be sure to unsubscribe when finished Connectivity.ConnectivityChanged += OnConnectivityChanged; IsInternetConnected = CheckConnection(); } #endregion #region Destructor ~NetworkConnectivity() { Connectivity.ConnectivityChanged -= OnConnectivityChanged; } #endregion #region Handle Network Connection public static bool CheckConnection() { var current = Connectivity.NetworkAccess; if (current == NetworkAccess.Internet) return true; else return false; } private void OnConnectivityChanged(object sender, ConnectivityChangedEventArgs e) { var access = e.NetworkAccess; var profiles = e.ConnectionProfiles; switch (access) { case NetworkAccess.Internet: IsInternetConnected = true; ShowInternetConnection(true); break; case NetworkAccess.None: IsInternetConnected = false; ShowInternetConnection(false); break; case NetworkAccess.Local: IsInternetConnected = false; ShowInternetConnection(false); break; case NetworkAccess.Unknown: System.Console.Write("A problem has occurred with your network connection."); break; default: break; } } private void ShowInternetConnection(bool isInternetAvail) { // Set Internet connection view in every page in header App.Instance.SetInternetConnectionView(isInternetAvail); } #endregion } }
4 – Now, Create Instance static property in App.xaml.cs
private static App _instance; public static App Instance { get { return _instance; } set { _instance = value; } }
5 – Initialize Instance static variable in constructor of App.xaml.cs
public App () { InitializeComponent(); Instance = this; MainPage = new NavigationPage(new MainPage()); }
6 – Now, Initialize NetworkConnectivity.cs class in OnStart() method.
protected override void OnStart () { // Register Network Connectivity Change Event NetworkConnectivity networkConnectivityHelper = new NetworkConnectivity(); }
7 – Now, Coming to UI part first of all we need to create ControlTemplate for each network state in App.xaml
![Internet connection status](https://learnmobiledevelopment.com/wp-content/uploads/2022/11/InternetTemplates.png)
<!-- Page Header (InternetConnection view) Template --> <ControlTemplate x:Key="InternetConnTemplate"> <StackLayout Spacing="0"> <BoxView BackgroundColor="#2196F3" HeightRequest="55" IsVisible="{OnPlatform Android='False', iOS='True'}" /> <ContentPresenter /> </StackLayout> </ControlTemplate> <!-- Empty Template --> <ControlTemplate x:Key="EmptyTemplate"> <StackLayout Spacing="0"> <BoxView BackgroundColor="#2196F3" HeightRequest="55" IsVisible="{OnPlatform Android='False', iOS='True'}" /> <ContentPresenter /> </StackLayout> </ControlTemplate> <!-- Online Template --> <ControlTemplate x:Key="OnlineTemplate"> <StackLayout Spacing="0"> <BoxView BackgroundColor="#2196F3" HeightRequest="55" IsVisible="{OnPlatform Android='False', iOS='True'}" /> <Frame x:Name="FrameBackground" Padding="0,2,0,2" BackgroundColor="#32CD32" CornerRadius="0" HasShadow="False"> <Label x:Name="LabelTitle" FontAttributes="Bold" HorizontalOptions="CenterAndExpand" Text="Internet Connected" TextColor="White" VerticalOptions="CenterAndExpand" /> </Frame> <ContentPresenter /> </StackLayout> </ControlTemplate> <!-- Offline Template --> <ControlTemplate x:Key="OfflineTemplate"> <StackLayout Spacing="0"> <BoxView BackgroundColor="#2196F3" HeightRequest="55" IsVisible="{OnPlatform Android='False', iOS='True'}" /> <Frame Padding="0,2,0,2" BackgroundColor="Red" CornerRadius="0" HasShadow="False"> <Label FontAttributes="Bold" HorizontalOptions="CenterAndExpand" Text="No internet connection" TextColor="White" VerticalOptions="CenterAndExpand" /> </Frame> <ContentPresenter /> </StackLayout> </ControlTemplate>
8 – Now, We will need to change the template at run time when the network state will change
- So, Create a SetInternetConnectionView() method in App.xaml.cs If you will see, this method is called from the NetworkConnectivity.cs class.
#region Set Internet Connection View public void SetInternetConnectionView(bool isInternetAvail) { Device.BeginInvokeOnMainThread(() => { if (isInternetAvail) { App.Current.Resources["InternetConnTemplate"] = App.Current.Resources["OnlineTemplate"]; StartTimerFor4Second(); } else { App.Current.Resources["InternetConnTemplate"] = App.Current.Resources["OfflineTemplate"]; } }); } private static void RemoveTopInternetConnView() { App.Current.Resources["InternetConnTemplate"] = App.Current.Resources["EmptyTemplate"]; } private void StartTimerFor4Second() { System.Timers.Timer timer = new System.Timers.Timer(); timer.Interval = 4000; timer.Enabled = true; timer.Elapsed += OnTimedEvent; } private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e) { try { (source as System.Timers.Timer).Enabled = false; (source as System.Timers.Timer).Dispose(); Device.BeginInvokeOnMainThread(() => { RemoveTopInternetConnView(); }); } catch (Exception ex) { } } #endregion
State Explanation
Normal State : Empty Template shows in normal state. Offline State : Offline Template shows when no internet connection is available. Online State : Online Template shows when internet connection comes back. |
- I have used a timer for displaying online templates for only 4 seconds.
- In case of no internet connection we will need to call the SetInternetConnectionView() method from the OnResume() method and Constructors of App.xaml.cs.
protected override void OnResume () { if (!NetworkConnectivity.CheckConnection()) SetInternetConnectionView(false); }
public App () { InitializeComponent(); Instance = this; MainPage = new NavigationPage(new MainPage()); if (!NetworkConnectivity.CheckConnection()) SetInternetConnectionView(false); }
9 – At last we need to set the InternetConnTemplate control template in the root page of all pages
ControlTemplate=”{DynamicResource InternetConnTemplate}” |
Example
![Internet connection status](https://learnmobiledevelopment.com/wp-content/uploads/2022/11/InternetStatusControlTemplate.png)
10 – Result
That’s all for now!
You can check the full source code here.
Happy Coding! 😀
You may also like