Delpin Susai Raj Friday, 23 October 2020

Xamarin.Forms - Mobile Network Speed Check(Slow or Fast) in Android

In this blog post, you will learn how to check you mobile network speed(slow or speed) using android native in Xamarin.Forms.



Introduction

Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

Prerequisites

  • Visual Studio 2017 or later (Windows or Mac)

Setting up a Xamarin.Forms Project

 Start by creating a new Xamarin.Forms project. You wíll learn more by going through the steps yourself.

Create a new or existing Xamarin forms(.Net standard) Project. With Android and iOS Platform. 


Create a Interface

public interface INetwork
{
bool IsConnected();
bool IsConnectedFast();
}
view raw INetwork.cs hosted with ❤ by GitHub

Create a NetworkConnectivity

Following code will check the Mobile network connection and Check the Network status whether speed or slow.

NetworkConnectivity.cs

public class NetworkConnectivity
{
public static NetworkInfo GetNetworkInfo(Context context)
{
ConnectivityManager cm = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
return cm.ActiveNetworkInfo;
}
/**
* Check if there is any connectivity
* @param context
* @return
*/
public static bool IsConnected(Context context)
{
NetworkInfo info = NetworkConnectivity.GetNetworkInfo(context);
return (info != null && info.IsConnected);
}
/**
* Check if there is any connectivity to a Wifi network
* @param context
// @param type
* @return
*/
public static bool IsConnectedWifi(Context context)
{
NetworkInfo info = NetworkConnectivity.GetNetworkInfo(context);
return (info != null && info.IsConnected && info.Type == ConnectivityType.Wifi);
}
/**
* Check if there is any connectivity to a mobile network
* @param context
// @param type
* @return
*/
public static bool IsConnectedMobile(Context context)
{
NetworkInfo info = NetworkConnectivity.GetNetworkInfo(context);
return (info != null && info.IsConnected && info.Type == ConnectivityType.Mobile);
}
/**
* Check if there is fast connectivity
* @param context
* @return
*/
public static bool IsConnectedFast(Context context)
{
NetworkInfo info = NetworkConnectivity.GetNetworkInfo(context);
TelephonyManager tm = TelephonyManager.FromContext(context);
return (info != null && info.IsConnected && NetworkConnectivity.IsConnectionFast(info.Type, tm.NetworkType));
}
/**
* Check if the connection is fast
* @param type
* @param subType
* @return
*/
public static bool IsConnectionFast(ConnectivityType type, NetworkType subType)
{
if (type == ConnectivityType.Wifi)
{
return true;
}
else if (type == ConnectivityType.Mobile)
{
switch (subType)
{
//case TelephonyManager.NETWORK_TYPE_1xRTT:
case NetworkType.OneXrtt:
return false; // ~ 50-100 kbps
//case TelephonyManager.NETWORK_TYPE_CDMA:
case NetworkType.Cdma:
return false; // ~ 14-64 kbps
//case TelephonyManager.NETWORK_TYPE_EDGE:
case NetworkType.Edge:
return false; // ~ 50-100 kbps
//case TelephonyManager.NETWORK_TYPE_EVDO_0:
case NetworkType.Evdo0:
return true; // ~ 400-1000 kbps
//case TelephonyManager.NETWORK_TYPE_EVDO_A:
case NetworkType.EvdoA:
return true; // ~ 600-1400 kbps
//case TelephonyManager.NETWORK_TYPE_GPRS:
case NetworkType.Gprs:
return false; // ~ 100 kbps
//case TelephonyManager.NETWORK_TYPE_HSDPA:
case NetworkType.Hsdpa:
return true; // ~ 2-14 Mbps
//case TelephonyManager.NETWORK_TYPE_HSPA:
case NetworkType.Hspa:
return true; // ~ 700-1700 kbps
//case TelephonyManager.NETWORK_TYPE_HSUPA:
case NetworkType.Hsupa:
return true; // ~ 1-23 Mbps
//case TelephonyManager.NETWORK_TYPE_UMTS:
case NetworkType.Umts:
return true; // ~ 400-7000 kbps
/*
* Above API level 7, make sure to set android:targetSdkVersion
* to appropriate level to use these
*/
//case TelephonyManager.NETWORK_TYPE_EHRPD: // API level 11
case NetworkType.Ehrpd:
return true; // ~ 1-2 Mbps
//case TelephonyManager.NETWORK_TYPE_EVDO_B: // API level 9
case NetworkType.EvdoB:
return true; // ~ 5 Mbps
//case TelephonyManager.NETWORK_TYPE_HSPAP: // API level 13
case NetworkType.Hspap:
return true; // ~ 10-20 Mbps
//case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8
case NetworkType.Iden:
return false; // ~25 kbps
//case TelephonyManager.NETWORK_TYPE_LTE: // API level 11
case NetworkType.Lte:
return true; // ~ 10+ Mbps
// Unknown
//case TelephonyManager.NETWORK_TYPE_UNKNOWN:
case NetworkType.Unknown:
return false;
default:
return false;
}
}
else
{
return false;
}
}
public static bool IsHostReachable(string host)
{
if (string.IsNullOrEmpty(host))
return false;
bool isReachable = true;
Thread thread = new Thread(() =>
{
try
{
//isReachable = InetAddress.GetByName(host).IsReachable(2000);
/*
* It's important to note that isReachable tries ICMP ping and then TCP echo (port 7).
* These are often closed down on HTTP servers.
* So a perfectly good working API with a web server on port 80 will be reported as unreachable
* if ICMP and TCP port 7 are filtered out!
*/
//if (!isReachable){
URL url = new URL("http://" + host);
URLConnection connection = url.OpenConnection();
//if(connection.ContentLength != -1){
//isReachable = true;
if (connection.ContentLength == -1)
{
isReachable = false;
}
//}
}
catch (UnknownHostException e)
{
isReachable = false;
}
catch (IOException e)
{
isReachable = false;
}
});
thread.Start();
return isReachable;
}
}

Android Implementation

Here, Implement the Interface and return the network status.

NetworkHelper.cs

[assembly: Xamarin.Forms.Dependency(typeof(NetworkHelper))]
namespace NetworkPOC.Droid
{
public class NetworkHelper : INetwork
{
Context context = Android.App.Application.Context;
public bool IsConnected()
{
return NetworkConnectivity.IsConnected(context);
}
public bool IsConnectedFast()
{
return NetworkConnectivity.IsConnectedFast(context);
}
}
}


Consume the Network helper

Here, you will call the Network helper class and you will get the network speed.

MainPage.Xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="NetworkPOC.MainPage">
<StackLayout HorizontalOptions="Center" VerticalOptions="Start" Margin="0,150,0,0">
<Label FontSize="Large" Text="Xamarin Monkeys"/>
<Button Text="Check" Clicked="Button_Clicked"></Button>
</StackLayout>
</ContentPage>
view raw MainPage.xaml hosted with ❤ by GitHub


Here I shows the result in toast. 

MainPage.xaml.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Essentials;
using System.Net.Http;
namespace NetworkPOC
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
var current = Connectivity.NetworkAccess;
if (current == NetworkAccess.Internet)
{
bool isConnectionFast = DependencyService.Get<INetwork>().IsConnectedFast();
if (isConnectionFast)
DependencyService.Get<IToast>().ShowToast("Network Connection is good");
else
DependencyService.Get<IToast>().ShowToast("Network Connection is slow");
}
else
{
DependencyService.Get<IToast>().ShowToast("No Internet Connection");
}
}
}


Run



I hope you have understood you will learn how to check you mobile network speed(slow or speed) using android native in Xamarin.Forms.

Thanks for reading. Please share your comments and feedback. 

Happy Coding :)

Delpin Susai Raj Wednesday, 21 October 2020

Xamarin.Forms - Network Speed Monitor

 In this blog post, you will learn how to monitor you network speed in Xamarin.Forms.

Introduction

Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

Prerequisites

  • Visual Studio 2017 or later (Windows or Mac)

Setting up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You wíll learn more by going through the steps yourself.

Create a new or existing Xamarin forms(.Net standard) Project. With Android and iOS Platform.


 Network Monitor 

Now, create a network helper class for check network connectivity in xamarin.froms.

NetworkHelper.cs

public class NetworkHelper
{
public async Task<string> CheckInternetSpeed()
{
DateTime dt1 = DateTime.Now;
string internetSpeed;
try
{
var client = new HttpClient();
byte[] data = await client.GetByteArrayAsync("http://xamarinmonkeys.blogspot.com/");
DateTime dt2 = DateTime.Now; Console.WriteLine("ConnectionSpeed: DataSize (kb) " + data.Length / 1024);
Console.WriteLine("ConnectionSpeed: ElapsedTime (secs) " + (dt2 - dt1).TotalSeconds);
internetSpeed = "ConnectionSpeed: (kb/s) " + Math.Round((data.Length / 1024) / (dt2 - dt1).TotalSeconds, 2);
}
catch (Exception ex)
{
internetSpeed = "ConnectionSpeed:Unknown Exception-" + ex.Message;
}
Console.WriteLine(internetSpeed);
return internetSpeed;
}
}


Consuming Network helper

Here, you will call the Network helper class and you will get the network speed.

MainPage.Xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="NetworkPOC.MainPage">
<StackLayout HorizontalOptions="Center" VerticalOptions="Start" Margin="0,150,0,0">
<Label FontSize="Large" Text="Xamarin Monkeys"/>
<Button Text="Check" Clicked="Button_Clicked"></Button>
</StackLayout>
</ContentPage>
view raw MainPage.Xaml hosted with ❤ by GitHub


Here I shows the result in toast. 

MainPage.xaml.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Essentials;
using System.Net.Http;
namespace NetworkPOC
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private async void Button_Clicked(object sender, EventArgs e)
{
if (current == NetworkAccess.Internet)
{
var speed=await CheckInternetSpeed();
DependencyService.Get<IToast>().ShowToast(speed);
}
else
{
DependencyService.Get<IToast>().ShowToast("No Internet Connection");
}
}
}
}


Run



I hope you have understood you will learn how to check network speed in Xamarin.Forms.

Thanks for reading. Please share your comments and feedback. 

Happy Coding :)

Delpin Susai Raj Monday, 12 October 2020

Enable Dark Mode in iOS Simulator

 

Make sure your iOS version should be iOS 13 or Later

Goto Settings in your iOS Simulator.

Now scroll down in settings, you're able to see the Developer in the list. Click Developer.

Now, Enable the Dark Appearance toggle. Your simulator will behave dark mode.

Your simulator is Dark Mode.

I hope you have understood how to enable the dark mode in iOS Simulator.

Thanks for reading. Please share your comments and feedback. Happy Coding :)

Xamarin.Forms - Support Dark Mode

In this blog post, you will learn how to give support Dark Mode in Xamarin.Forms.

Introduction

Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

Dark Mode


Nowadays iOS and Android apps should support both Dark and Light Theme.

Prerequisites

  • Visual Studio 2017 or later (Windows or Mac)

Setting up a Xamarin.Forms Project

 Start by creating a new Xamarin.Forms project. You wíll learn more by going through the steps yourself.

Create a new or existing Xamarin forms(.Net standard) Project. With Android and iOS Platform. 

Create a Theme

Create a ResourceDictionary for both Light and Dark Theme.

DarkTheme.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="DarkModePOC.Common.Styles.DarkTheme">
<Color x:Key="BackgroundColor">#FF000000</Color>
<Color x:Key="FrameColor">#FF1f1f1f</Color>
<Color x:Key="TextPrimaryColor">#B0FFFFFF</Color>
<Color x:Key="TextSecondaryColor">#eFeFeF</Color>
<Style x:Key="Title" TargetType="Label">
<Setter Property="TextColor" Value="{StaticResource TextPrimaryColor}"/>
<Setter Property="FontAttributes" Value="Bold"/>
<Setter Property="FontSize" Value="Large"/>
</Style>
</ResourceDictionary>
view raw DarkTheme.xaml hosted with ❤ by GitHub

LightTheme.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="DarkModePOC.Common.Styles.LightTheme">
<Color x:Key="BackgroundColor">#FFe0e0e0</Color>
<Color x:Key="FrameColor">#FFFFFFFF</Color>
<Color x:Key="TextPrimaryColor">#B0000000</Color>
<Color x:Key="TextSecondaryColor">#858585</Color>
<Style x:Key="Title" TargetType="Label">
<Setter Property="TextColor" Value="{StaticResource TextPrimaryColor}"/>
<Setter Property="FontSize" Value="Large"/>
</Style>
</ResourceDictionary>
view raw LightTheme.xaml hosted with ❤ by GitHub


Set App Theme

In app.xaml you can set the default theme.

App.xaml

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="DarkModePOC.App">
<Application.Resources>
<ResourceDictionary Source="Common/Styles/LightTheme.xaml" />
</Application.Resources>
</Application>
view raw App.xaml hosted with ❤ by GitHub

Now, Create a Enum in App.xaml.cs

public partial class App : Application
{
public static Theme AppTheme { get; set; }
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
}
protected override void OnStart()
{
}
protected override void OnSleep()
{
}
protected override void OnResume()
{
}
public enum Theme
{
Light,
Dark
}
}
view raw App.xaml.cs hosted with ❤ by GitHub

Create a Interface

Create a interface for set Theme at runtime.

public interface IAppTheme
{
void SetAppTheme(Theme theme);
}
view raw IAppTheme hosted with ❤ by GitHub


iOS Implementation

Below code to change the Theme at runtime.

ThemeHelper.cs


[assembly:Dependency(typeof(DarkModePOC.iOS.ThemeHelper))]
namespace DarkModePOC.iOS
{
public class ThemeHelper : IAppTheme
{
public void SetAppTheme(App.Theme theme)
{
SetTheme(theme);
}
void SetTheme(Theme mode)
{
if (mode == Theme.Dark)
{
if (App.AppTheme == Theme.Dark)
return;
App.Current.Resources = new DarkTheme();
}
else
{
if (App.AppTheme != Theme.Dark)
return;
App.Current.Resources = new LightTheme();
}
App.AppTheme = mode;
}
}
}
view raw ThemeHelper.cs hosted with ❤ by GitHub


Android Implementation

Below code to change the Theme at runtime.

ThemeHelper.cs


[assembly: Dependency(typeof(DarkModePOC.Droid.ThemeHelper))]
namespace DarkModePOC.Droid
{
public class ThemeHelper : IAppTheme
{
public void SetAppTheme(App.Theme theme)
{
SetTheme(theme);
}
void SetTheme(Theme mode)
{
if (mode == Theme.Dark)
{
if (App.AppTheme == Theme.Dark)
return;
App.Current.Resources = new DarkTheme();
}
else
{
if (App.AppTheme != Theme.Dark)
return;
App.Current.Resources = new LightTheme();
}
App.AppTheme = mode;
}
}
}
view raw ThemeHelper.cs hosted with ❤ by GitHub


Consuming the Styles


Now, you can use the resource "DynamicResource BackgroundColor" like this.


<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
BackgroundColor="{DynamicResource BackgroundColor}"
x:Class="DarkModePOC.MainPage">
<StackLayout HorizontalOptions="Center" VerticalOptions="Center">
<!-- Place new controls here -->
<Switch x:Name="themeToggle" IsToggled="False" Toggled="Switch_Toggled"/>
<Label TextColor="{DynamicResource TextSecondaryColor}" Text=" sample"/>
<Button HorizontalOptions="Center" VerticalOptions="Center" TextColor="Red" Text="Next Page" Clicked="Button_Clicked" />
</StackLayout>
</ContentPage>
view raw MainPage.xaml hosted with ❤ by GitHub


private void Switch_Toggled(object sender, ToggledEventArgs e)
{
var toggleStatus = themeToggle.IsToggled;
SetTheme(toggleStatus);
}
void SetTheme(bool status)
{
Theme themeRequested;
if (status)
{
themeRequested = Theme.Dark;
}
else
{
themeRequested = Theme.Light;
}
DependencyService.Get<IAppTheme>().SetAppTheme(themeRequested);
}


Click the "Play" button to try it out.

Dark Mode


Light Mode

I hope you have understood you will learn how to give support Dark Mode in Xamarin.Forms..

Thanks for reading. Please share your comments and feedback. 

Happy Coding :)