Skip to content

Learn Mobile Development

Alamgeer's Blog

Menu
  • Home
  • Privacy Policy
Menu
Internet connection status

How to check internet connection continuously in Xamarin Forms

Posted on November 20, 2022January 18, 2023 by Learn Mobile Development

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

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
 
<!--  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

10 – Result

That’s all for now!

You can check the full source code here.

Happy Coding! 😀

You may also like

Rotate views on orientation change

How to rotate views on orientation change in Xamarin Forms

DockLayout in MAUI

How to use DockLayout in MAUI

Post Views: 408
Share article with

Leave a Reply Cancel reply

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

I'm Alamgeer Ashraf and having 9+ years of experience in enterprises mobile application development with Xamarin Native, Xamarin Forms & .Net MAUI.

Archives

  • February 2023 (1)
  • January 2023 (9)
  • December 2022 (5)
  • November 2022 (6)

Latest Posts

  • Prevent Dark Mode in Xamarin forms
    How to Prevent Dark Mode in Xamarin formsFebruary 3, 2023
  • apply color to Images
    How to apply color to Images and Icons in MAUIJanuary 30, 2023
  • iOS Large Page Title
    How to set iOS large page title in MAUIJanuary 26, 2023
  • Change StatusBar Color
    How to change StatusBar color in MAUIJanuary 22, 2023
  • Item reordering to CollectionView
    How to apply item reordering to CollectionView GridItemsLayout in MAUIJanuary 18, 2023

Popular Posts

  • Implementation Of Biometric Authentication in Xamarin Forms
  • .Net MAUI – The Latest CarouselView with IndicatorView
  • How to rotate views on orientation change in Xamarin Forms

Latest Comments

  1. Randyperly on How to use StateContainer in MAUIOctober 18, 2024

    very good _________________ netgame casino бездепозитный бонус

  2. SmiSew on How to use StateContainer in MAUIOctober 10, 2024

    Thanks for the post _________________ pin up casino бест

  3. StavkiTarve on How to use StateContainer in MAUIOctober 7, 2024

    interesting post _________________ слоты в 1xbet приложение

  4. Luke on How to use drag and drop gesture to CollectionView in MAUISeptember 25, 2024

    Thanks very much!

  5. Tony - Nhan Nguyen Lhoa Minh on How to apply item reordering to CollectionView GridItemsLayout in MAUIMarch 28, 2024

    That would be an amazing solution. It's easy to comprehend. Thank you very much.

Our Visitor

0 0 7 8 5 6
Users Today : 3
Users Yesterday : 4
Users Last 7 days : 27
Users Last 30 days : 145
Users This Month : 77
Total views : 14076
How to use ObservableObject in MAUI for Data Binding
Trending
How to use ObservableObject in MAUI for Data Binding

Category

  • .Net MAUI
  • MAUI Community Toolkit
  • MVVM
  • Xamarin Community Toolkit
  • Xamarin Forms

Contact Me

  • LinkedIn
      © 2025 Learn Mobile Development