Pages

Wednesday, 9 January 2019

How to continuously check internet connection in Xamarin Forms

Does your app need to constantly check it’s internet connectivity?
Do you want to inform your user that he/she is disconnected from the net?
In this post, we will create a quick wifi connection detector while the app is running.

Step 1: Add any connectivity images in your Android drawable directory and iOS Resources directory. Images should be both connected and disconnected images.





Step 2: Search xam.plugin.connectivity in the Manage NuGet Package Solution.




Step 3: Install the xam.plugin.connectivity NuGet package in all your projects.



 MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="CheckConn.MainPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:CheckConn">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="100" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="5*" />
            <ColumnDefinition Width="5*" />
        </Grid.ColumnDefinitions>


        <Image Grid.Column="0" Source="{Binding Conn}" />

        <Label
            Grid.Column="1"
            FontSize="Large"
            HorizontalOptions="Center"
            Text="{Binding x}"
            VerticalOptions="Center" />
    </Grid>
</ContentPage>

MainPage.xaml.cs file(Code behind)

using Xamarin.Forms;

namespace CheckConn
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            BindingContext = new MainViewModel();
        }
    }
}

Now for View Model (MainViewModel.cs)

using CheckConn.Annotations;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Plugin.Connectivity;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace CheckConn
{
    internal class MainViewModel : INotifyPropertyChanged
    {
        private string _conn;
        private string _x;
        public string Conn
        {
            get => _conn;
            set
            {
                _conn = value;
                OnPropertyChanged();
            }
        }

        public string x
        {
            get => _x;
            set
            {
                _x = value;
                OnPropertyChanged();
            }
        }
        public MainViewModel()
        {
            CheckWifiOnStart();
            CheckWifiContinuously();
        }

        public async void CheckWifiOnStart()
        {
            x = "0 kb/sec";
            Conn = CrossConnectivity.Current.IsConnected ? "online.png" : "offline.png";
            await StartTest();
        }

        public void CheckWifiContinuously()
        {
           Device.StartTimer(TimeSpan.FromSeconds(1), OnTimerTick);

            CrossConnectivity.Current.ConnectivityChanged += (sender, args) =>
            {
                x = "0 kb/sec";
                Conn = args.IsConnected ? "online.png" : "offline.png";
              

            };
        }
        bool  OnTimerTick()
        {
            Conn = CrossConnectivity.Current.IsConnected ? "online.png" : "offline.png";
            StartTest();
            return true;
        }
        public async Task StartTest()
        {
            try
            {
                //string url =
                //"http://puresourcecode.com/file.axd?file=/SpeedTest/1024kb.txt";

               string url =
              "https://www.google.com/";

               HttpClient client = new HttpClient();

                // get current tickcount
                double starttime = Environment.TickCount;

                // download file from the specified URL,
                // and save it to C:\speedtest.txt
                // in your project change the path of the following line
                var httpResponse = await client.GetAsync(url);
                byte[] dataBuffer =
                       await httpResponse.Content.ReadAsByteArrayAsync();

                // get current tickcount
                double endtime = Environment.TickCount;

                // how many seconds did it take?
                // we are calculating this by subtracting starttime from
                // endtime and dividing by 1000 (since the tickcount is in
                // miliseconds 1000 ms = 1 sec)
                double SecondsForOneMb = Math.Floor(endtime - starttime) / 1000;

                // calculate download rate in kb per sec.
                // this is done by dividing 1024 by the number of seconds it
                // took to download the file (1024 bytes = 1 kilobyte)
                double KbSeconds = Math.Round(1024 / SecondsForOneMb);
                x = KbSeconds.ToString() + "kb/sec";
            }
            catch(Exception ex)
            {
                x = "0 kb/sec";
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Full source code link : https://drive.google.com/open?id=1xH_GvTJpmPUgFez9G3xm8SP0QyfcjXfb



4 comments:

  1. It was great experience after reading this. thanks for sharing such good stuff with us.
    Internet Speed Test

    ReplyDelete
  2. This article provides the options of internet access for remote areas and describes both the pros and cons of satellite broadband internet. It then goes through the top three satellite internet providers with a concise review. KickassTorrents proxy

    ReplyDelete
  3. You might comment on the order system of the blog. You should chat it's splendid. Your blog audit would swell up your visitors. I was very pleased to find this site.I wanted to thank you for this great read!! wifi speed test

    ReplyDelete