Pages

Wednesday, 9 January 2019

Xamarin.Essentials

Xamarin.Essentials

https://github.com/xamarin/Essentials

Xamarin.Essentials provides developers with cross-platform APIs for their mobile applications.
Android, iOS, and UWP offer unique operating system and platform APIs that developers have access to all in C# leveraging Xamarin. Xamarin.Essentials provides a single cross-platform API that works with any Xamarin.Forms, Android, iOS, or UWP application that can be accessed from shared code no matter how the user interface is created.
Xamarin.Essentials is built with the new SDK style projects with multi-targeting enabled. This means that all code for iOS, Android, and UWP exist inside of the Xamarin.Essentials project.
If building on Visual Studio 2017 simply open the solution and build the project.
If using Visual Studio for Mac the project can be built at the command line with MSBuild. To change the project type that you are working with simply edit Xamarin.Essentials.csproj and modify the TargetFrameworks for only the project type you want to use.


Where are the interfaces?

Some developers prefer an interface based programming model for dependency injection and testing of code. Xamarin.Essentials does not offer any interfaces and delivers straight API access via direct classes and static properties/methods. There are many reasons that Xamarin.Essentials is architected this way that include performance, simplicity, and ease of use. We also consider Xamarin.Essentials a core API of the platform just like System classes, HttpClient, and our platform bindings.
Additionally, we found most developers create their own interfaces even when using a library that have interfaces. They do this so they have control over the APIs they actually use, which may be a very small percentage of the overall APIs in the library. Creating your own IXamarinEssentials and exposing only the methods and properties you would like to use gives you more flexibility as Xamarin.Essentials grows and adds additional APIs. Using this type of architecture will enable you to both have dependency injection and work with unit testing.

Does Xamarin.Essentials replace plugins?

Plugins offer a wide variety of cross-platform APIs for developers to use in their applications. Plugins will still continue to grow and flourish as they can offer a wider range of APIs and handle unique scenarios that Xamarin.Essentials may not offer including additional platform support or add features unique to a single platform.





Xamarin.Essentials Accelerometer

he Accelerometer class lets you monitor the device's accelerometer sensor which indicates the acceleration of the device in three dimensional space.

Using Accelerometer

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
The Accelerometer functionality works by calling the Start and Stop methods to listen for changes to the acceleration. Any changes are sent back through the ReadingChanged event. Here is sample usage:
C#
 
public class AccelerometerTest
{
    // Set speed delay for monitoring changes.
    SensorSpeed speed = SensorSpeed.Ui;
 
    public AccelerometerTest()
    {
        // Register for reading changes, be sure to unsubscribe when finished
        Accelerometer.ReadingChanged += Accelerometer_ReadingChanged;
    }
 
    void Accelerometer_ReadingChanged(AccelerometerChangedEventArgs e)
    {
        var data = e.Reading;
        Console.WriteLine($"Reading: X: {data.Acceleration.X}, Y: {data.Acceleration.Y}, Z: {data.Acceleration.Z}");
        // Process Acceleration X, Y, and Z
    }
 
    public void ToggleAcceleromter()
    {
        try
        {
            if (Accelerometer.IsMonitoring)
              Accelerometer.Stop();
            else
              Accelerometer.Start(speed);
        }
        catch (FeatureNotSupportedException fnsEx)
        {
            // Feature not supported on device
        }
        catch (Exception ex)
        {
            // Other error has occurred.
        }
    }
}
Accelerometer readings are reported back in G. A G is a unit of gravitation force equal to that exerted by the earth's gravitational field (9.81 m/s^2).
The coordinate-system is defined relative to the screen of the phone in its default orientation. The axes are not swapped when the device's screen orientation changes.
The X axis is horizontal and points to the right, the Y axis is vertical and points up and the Z axis points towards the outside of the front face of the screen. In this system, coordinates behind the screen have negative Z values.
Examples:
·         When the device lies flat on a table and is pushed on its left side toward the right, the x acceleration value is positive.
·         When the device lies flat on a table, the acceleration value is +1.00 G or (+9.81 m/s^2), which correspond to the acceleration of the device (0 m/s^2) minus the force of gravity (-9.81 m/s^2) and normalized as in G.
·         When the device lies flat on a table and is pushed toward the sky with an acceleration of A m/s^2, the acceleration value is equal to A+9.81 which correspond to the acceleration of the device (+A m/s^2) minus the force of gravity (-9.81 m/s^2) and normalized in G.

Sensor Speed

  • Fastest – Get the sensor data as fast as possible (not guaranteed to return on UI thread).
  • Game – Rate suitable for games (not guaranteed to return on UI thread).
  • Normal – Default rate suitable for screen orientation changes.
  • Ui – Rate suitable for general user interface.

Xamarin.Essentials App Information

The AppInfo class provides information about your application.

Using AppInfo

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
The following information is exposed through the API:
C#
// Application Name
var appName = AppInfo.Name;
 
// Package Name/Application Identifier (com.microsoft.testapp)
var packageName = AppInfo.PackageName;
 
// Application Version (1.0.0)
var version = AppInfo.VersionString;
 
// Application Build Number (1)
var build = AppInfo.BuildString;

Xamarin.Essentials Battery

The Battery class lets you check the device's battery information and monitor for changes.
The Battery permission is required and must be configured in the Android project. This can be added in the following ways:
Open the AssemblyInfo.cs file under the Properties folder and add:
C#
[assembly: UsesPermission(Android.Manifest.Permission.Battery)]
OR Update Android Manifest:
Open the AndroidManifest.xml file under the Properties folder and add the following inside of the manifest node.
XML
<uses-permission android:name="android.permission.BATTERY" />
Or right click on the Anroid project and open the project's properties. Under Android Manifest find the Required permissions: area and check the Battery permission. This will automatically update the AndroidManifest.xml file.
Ios and Windows : No additional setup required.


Using Battery

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
Check current battery information:
C#
var level = Battery.ChargeLevel; // returns 0.0 to 1.0 or -1.0 if unable to determine.
 
var state = Battery.State;
 
switch (state)
{
    case BatteryState.Charging:
        // Currently charging
        break;
    case BatteryState.Full:
        // Battery is full
        break;
    case BatteryState.Discharging:
    case BatteryState.NotCharging:
        // Currently discharging battery or not being charged
        break;
    case BatteryState.NotPresent:
        // Battery doesn't exist in device (desktop computer)
    case BatteryState.Unknown:
        // Unable to detect battery state
        break;
}
 
var source = Battery.PowerSource;
 
switch (source)
{
    case BatteryPowerSource.Battery:
        // Being powered by the battery
        break;
    case BatteryPowerSource.Ac:
        // Being powered by A/C unit
        break;
    case BatteryPowerSource.Usb:
        // Being powered by USB cable
        break;
    case BatteryPowerSource.Wireless:
        // Powered via wireless charging
        break;
    case BatteryPowerSource.Unknown:
        // Unable to detect power source
        break;
}
Whenever any of the battery's properties chagne an event is triggered:
C#
public class BatteryTest
{
    public BatteryTest()
    {
        // Register for battery changes, be sure to unsubscribe when needed
        Battery.BatteryChanged += Battery_BatteryChanged;
    }
 
    void Battery_BatteryChanged(BatteryChangedEventArgs   e)
    {
        var level = e.ChargeLevel;
        var state = e.State;
        var source = e.PowerSource;
        Console.WriteLine($"Reading: Level: {level}, State: {state}, Source: {source}");
    }
}

Platform Differences

Platform
Difference
iOS
Device must be used to test APIs.
iOS
Only will return Ac or Battery for PowerSource.
UWP
Only will return Ac or Battery for PowerSource.

Xamarin.Essentials Clipboard

The Clipboard class lets you copy and paste text to the system clipboard between applications.

Using Clipboard

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
To check if the Clipboard has text currently ready to be pasted:
C#
var hasText = Clipboard.HasText;
To set text to the Clipboard:
C#
ClipBoard.SetText("Hello World");
To read text from the Clipboard:
C#
var text = await Clipboard.GetTextAsync();

Xamarin.Essentials Compass

The Compass class lets you monitor the device's magnetic north heading.

Using Compass

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
The Compass functionality works by calling the Start and Stop methods to listen for changes to the compass. Any changes are sent back through the ReadingChanged event. Here is an example:
C#
public class CompassTest
{
    // Set speed delay for monitoring changes.
    SensorSpeed speed = SensorSpeed.Ui;
 
    public CompassTest()
    {
        // Register for reading changes, be sure to unsubscribe when finished
        Compass.ReadingChanged += Compass_ReadingChanged;
    }
 
    void Compass_ReadingChanged(CompassChangedEventArgs e)
    {
        var data = e.Reading;
        Console.WriteLine($"Reading: {data.HeadingMagneticNorth} degrees");
        // Process Heading Magnetic North
    }
 
    public void ToggleCompass()
    {
        try
        {
            if (Compass.IsMonitoring)
              Compass.Stop();
            else
              Compass.Start(speed);
        }
        catch (FeatureNotSupportedException fnsEx)
        {
            // Feature not supported on device
        }
        catch (Exception ex)
        {
            // Some other exception has occured
        }
    }
}

Sensor Speed

  • Fastest – Get the sensor data as fast as possible (not guaranteed to return on UI thread).
  • Game – Rate suitable for games (not guaranteed to return on UI thread).
  • Normal – Default rate suitable for screen orientation changes.
  • Ui – Rate suitable for general user interface.

Platform Implementation Specifics

Android does not provide a API for retrieving the compass heading. We utilize the accelerometer and magnetometer to calculate the magnetic north heading, which is recommended by Google.
In rare instances, you maybe see inconsistent results because the sensors need to be calibrated, which involves moving your device in a figure-8 motion. The best way of doing this is to open Google Maps, tap on the dot for your location, and select Calibrate compass.
Be aware that running multiple sensors from your app at the same time may adjust the sensor speed.

Xamarin.Essentials Connectivity

The Connectivity class lets you monitor for changes in the device's network conditions, check the current network access, and how it is currently connected.
To access the Connectivity functionality the following platform specific setup is required.
Android :
The AccessNetworkState permission is required and must be configured in the Android project. This can be added in the following ways:
Open the AssemblyInfo.cs file under the Properties folder and add:
C#
[assembly: UsesPermission(Android.Manifest.Permission.AccessNetworkState)]
OR Update Android Manifest:
Open the AndroidManifest.xml file under the Properties folder and add the following inside of the manifest node.
XML
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Or right click on the Anroid project and open the project's properties. Under Android Manifest find the Required permissions: area and check the Access Network State permission. This will automatically update the AndroidManifest.xml file.

Using Connectivity

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
Check current network access:
C#
var current = Connectivity.NetworkAccess;
 
if (current == NetworkAccess.Internet)
{
    // Connection to internet is available
}
Network access falls into the following categories:
  • Internet – Local and internet access.
  • ConstrainedInternet – Limited internet access. Indicates captive portal connectivity, where local access to a web portal is provided, but access to the Internet requires that specific credentials are provided via a portal.
  • Local – Local network access only.
  • None – No connectivity is available.
  • Unknown – Unable to determine internet connectivity.
You can check what type of connection profile the device is actively using:
C#
var profiles = Connectivity.Profiles;
if (profiles.Contains(ConnectionProfile.WiFi))
{
    // Active Wi-Fi connection.
}
Whenever the connection profile or network access changes you can receive an event when triggered:
C#
public class ConnectivityTest
{
    public ConnectivityTest()
    {
        // Register for connectivity changes, be sure to unsubscribe when finished
        Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
    }
 
    void Connectivity_ConnectivityChanged(ConnectivityChangedEventArgs  e)
    {
        var access = e.NetworkAccess;
        var profiles = e.Profiles;
    }
}

Limitations

It is important to note that it is possible that Internet is reported by NetworkAccess but full access to the web is not available. Due to how connectivity works on each platform it can only guarantee that a connection is available. For instance the device may be connected to a Wi-Fi network, but the router is disconnected from the internet. In this instance Internet may be reported, but an active connection is not available.
IOS and Windows : No additional setup required.

Xamarin.Essentials Data Transfer

The DataTransfer class enables an application to share data such as text and web links to other applications on the device.

Using Data Transfer

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
The Data Transfer functionality works by calling the RequestAsync method with a data request payload that includes information to share to other applications. Text and Uri can be mixed and each platform will handle filtering based on content.
C#
 
public class DataTransferTest
{
    public async Task ShareText(string text)
    {
        await DataTransfer.RequestAsync(new ShareTextRequest
            {
                Text = text,
                Title = "Share Text"
            });
    }
 
    public async Task ShareUri(string uri)
    {
        await DataTransfer.RequestAsync(new ShareTextRequest
            {
                Uri = uri,
                Title = "Share Web Link"
            });
    }
}
User interface to share to external application that appears when request is made:

Platform Differences

Platform
Difference
Android
Subject property is used for desired subject of a message.
iOS
Subject not used.
iOS
Title not used.
UWP
Title will default to Application Name if not set.
UWP
Subject not used.

Xamarin.Essentials Device Information

he DeviceInfo class provides information about the device the application is running on.

Using DeviceInfo

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
The following information is exposed through the API:
C#
// Device Model (SMG-950U)
var device = DeviceInfo.Model;
 
// Manufacturer (Samsung)
var manufacturer = DeviceInfo.Manufacturer;
 
// Device Name (Motz's iPhone)
var deviceName = DeviceInfo.Name;
 
// Operating System Version Number (7.0)
var version = DeviceInfo.VersionString;
 
// Platform (Android)
var platform = DeviceInfo.Platform;
 
// Idiom (Phone)
var idiom = DeviceInfo.Idiom;
 
// Device Type (Physical)
var deviceType = DeviceInfo.DeviceType;

Platforms

DeviceInfo.Platform correlates to a constant string that maps to the operating system. The values can be checked with the Platforms class:
  • DeviceInfo.Platforms.iOS – iOS
  • DeviceInfo.Platforms.Android – Android
  • DeviceInfo.Platforms.UWP – UWP
  • DeviceInfo.Platforms.Unsupported – Unsupported

Idioms

DeviceInfo.Idiom correlates a constant string that maps to the type of device the application is running on. The values can be checked with the Idioms class:
  • DeviceInfo.Idioms.Phone – Phone
  • DeviceInfo.Idioms.Tablet – Tablet
  • DeviceInfo.Idioms.Desktop – Desktop
  • DeviceInfo.Idioms.TV – TV
  • DeviceInfo.Idioms.Unsupported – Unsupported

Device Type

DeviceInfo.DeviceType correlates an enumeration to determine if the application is runing on a physical or vitual device. A virtual device is a simulator or emulator.

Xamarin.Essentials File System Helpers

The FileSystem class contains a series of helpers to find the application's cache and data directories and open files inside of the app package.

Using File System Helpers

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
To get the application's directory to store cache data. Cache data can be used for any data that needs to persist longer than temporary data, but should not be data that is required to properly operate.
C#
var cacheDir = FileSystem.CacheDirectory;
To get the application's top-level diredctory for any files that are not user data files. These files are backed up with the operating system syncing framework. See Platform Implementation Specifics below.
C#
var mainDir = FileSystem.AppDataDirectory;
To open a file that is bundled into the application package:
C#
 using (var stream = await FileSystem.OpenAppPackageFileAsync(templateFileName))
 {
    using (var reader = new StreamReader(stream))
    {
        var fileContents = await reader.ReadToEndAsync();
    }
 }

Platform Implementation Specifics

  • CacheDirectory – Returns the Library/Caches directory.
  • AppDataDirectory – Returns the Library directory that is backed up by iTunes and iCloud.
Add any file into the Resources folder in the iOS project and mark the Build Action as BundledResource to use it with OpenAppPackageFileAsync.

Xamarin.Essentials Email

The Email class enables an application to open the default email application with a specified information including subject, body, and recepients (TO, CC, BCC).

Using Email

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
The Email functionality works by calling the ComposeAsync method an EmailMessage that contains information about the email:
C#
public class EmailTest
{
    public async Task SendEmail(string subject, string, body, List<string> recipients)
    {
        try
        {
            var message = new EmailMessage
            {
                Subject = subject,
                Body = body,
                To = recipients,
                //Cc = ccRecipients,
                //Bcc = bccRecipients
            }
            await Email.ComposeAsync(message);
        }
        catch (FeatureNotSupportedException fbsEx)
        {
            // Sms is not supported on this device
        }
        catch (Exception ex)
        {
            // Some other exception occured
        }
    }
}

Xamarin.Essentials Flashlight

The Flashlight class has the ability to turn on or off the device's camera flash to turn it into a flashlight.
The Flashlight and Camera permissions are required and must be configured in the Android project. This can be added in the following ways:
Open the AssemblyInfo.cs file under the Properties folder and add:
C#
[assembly: UsesPermission(Android.Manifest.Permission.Flashlight)]
[assembly: UsesPermission(Android.Manifest.Permission.Camera)]
OR Update Android Manifest:
Open the AndroidManifest.xml file under the Properties folder and add the following inside of the manifest node.
XML
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.CAMERA" />
Or right click on the Anroid project and open the project's properties. Under Android Manifest find the Required permissions: area and check the FLASHLIGHT and CAMERA permissions. This will automatically update the AndroidManifest.xml file.
By adding these permissions Google Play will automatically filter out devices without specific hardware. You can get around this by adding the following to your AssemblyInfo.cs file in your Android project:
C#
[assembly: UsesFeature("android.hardware.camera", Required = false)]
[assembly: UsesFeature("android.hardware.camera.autofocus", Required = false)]

Using Flashlight

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
The flashlight can be turned on and off through the TurnOnAsync and TurnOffAsync methods:
C#
try
{
    // Turn On
    await Flashlight.TurnOnAsync();
 
    // Turn Off
    await Flashlight.TurnOffAsync();
}
catch (FeatureNotSupportedException fnsEx)
{
    // Handle not supported on device exception
}
catch (PermissionException pEx)
{
    // Handle permission exception
}
catch (Exception ex)
{
    // Unable to turn on/off flashlight
}

Platform Implementation Specifics

The Flashlight class has been optmized based on the device's operating system.

API Level 23 and Higher

On newer API levels, Torch Mode will be used to turn on or off the flash unit of the device.

API Level 22 and Lower

A camera surface texture is created to turn on or off the FlashMode of the camera unit.
IOS : AVCaptureDevice is used to turn on and off the Torch and Flash mode of the device.
https://developer.xamarin.com/api/type/AVFoundation.AVCaptureDevice/

Windows : Lamp is used to detect the first lamp on the back of the device to turn on or off.
https://docs.microsoft.com/en-us/uwp/api/windows.devices.lights.lamp

Xamarin.Essentials Geocoding

The Geocoding class provides APIs to geocode a placemark to a positional coordinates and reverse geocode coordincates to a placemark.
To access the Geocoding functionality the following platform specific setup is required.

Using Geocoding

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
Getting location coordinates for an address:
C#
try
{
    var address =  "Microsoft Building 25 Redmond WA USA";
    var locations = await Geocoding.GetLocationsAsync(address);
 
    var location = locations?.FirstOrDefault();
    if (location != null)
    {
        Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}");
    }
}
catch (FeatureNotSupportedException fnsEx)
{
    // Feature not supported on device
}
catch (Exception ex)
{
    // Handle exception that may have occured in geocoding
}
Getting placemarks for an existing set of coordinates:
C#
try
{
    var lat = 47.673988;
    var lon = -122.121513;
 
    var placemarks = await Geocoding.GetPlacemarksAsync(lat, lon);
 
    var placemark = placemarks?.FirstOrDefault();
    if (placemark != null)
    {
        var geocodeAddress =
            $"AdminArea:       {placemark.AdminArea}\n" +
            $"CountryCode:     {placemark.CountryCode}\n" +
            $"CountryName:     {placemark.CountryName}\n" +
            $"FeatureName:     {placemark.FeatureName}\n" +
            $"Locality:        {placemark.Locality}\n" +
            $"PostalCode:      {placemark.PostalCode}\n" +
            $"SubAdminArea:    {placemark.SubAdminArea}\n" +
            $"SubLocality:     {placemark.SubLocality}\n" +
            $"SubThoroughfare: {placemark.SubThoroughfare}\n" +
            $"Thoroughfare:    {placemark.Thoroughfare}\n";
 
        Console.WriteLine(geocodeAddress);
    }
}
catch (FeatureNotSupportedException fnsEx)
{
    // Feature not supported on device
}
catch (Exception ex)
{
    // Handle exception that may have occurred in geocoding
}
IOS : No additional setup required.
UWP : A Bing maps API key is required to use geocoding funcationality. Sign up for a free Bing Maps account. Under My account > My keys create a new key and fill out information based on your application type.
Early on in your application's life before calling any Geocoding methods set the API key:
C#
Geocoding.MapKey = "YOUR-KEY-HERE";

Xamarin.Essentials Gyroscope

The Gyroscope class lets you monitor the device's gyroscope sensor which is the rotation around the device's three primary axes.

Using Gyroscope

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
The Gyroscope functionality works by calling the Start and Stop methods to listen for changes to the gyroscope. Any changes are sent back through the ReadingChanged event. Here is sample usage:
C#
 
public class GyroscopeTest
{
    // Set speed delay for monitoring changes.
    SensorSpeed speed = SensorSpeed.Ui;
 
    public GyroscopeTest()
    {
        // Register for reading changes.
        Gyroscope.ReadingChanged += Gyroscope_ReadingChanged;
    }
 
    void Gyroscope_ReadingChanged(GyroscopeChangedEventArgs e)
    {
        var data = e.Reading;
        // Process Angular Velocity X, Y, and Z
        Console.WriteLine($"Reading: X: {data.AngularVelocity.X}, Y: {data.AngularVelocity.Y}, Z: {data.AngularVelocity.Z}");
    }
 
    public void ToggleGyroscope()
    {
        try
        {
            if (Gyroscope.IsMonitoring)
              Gyroscope.Stop();
            else
              Gyroscope.Start(speed);
        }
        catch (FeatureNotSupportedException fnsEx)
        {
            // Feature not supported on device
        }
        catch (Exception ex)
        {
            // Other error has occurred.
        }
    }
}

Sensor Speed

  • Fastest – Get the sensor data as fast as possible (not guaranteed to return on UI thread).
  • Game – Rate suitable for games (not guaranteed to return on UI thread).
  • Normal – Default rate suitable for screen orientation changes.
  • Ui – Rate suitable for general user interface.

Xamarin.Essentials Magnetometer

The Magnetometer class lets you monitor the device's magnetometer sensor which indicates the device's orientation relative to Earth's magnetic field.

Using Magnetometer

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
The Magnetometer functionality works by calling the Start and Stop methods to listen for changes to the magnetometer. Any changes are sent back through the ReadingChanged event. Here is sample usage:
C#
 
public class MagnetometerTest
{
    // Set speed delay for monitoring changes.
    SensorSpeed speed = SensorSpeed.Ui;
 
    public MagnetometerTest()
    {
        // Register for reading changes.
        Magnetometer.ReadingChanged += Magnetometer_ReadingChanged;
    }
 
    void Magnetometerr_ReadingChanged(MagnetometerChangedEventArgs e)
    {
        var data = e.Reading;
        // Process MagneticField X, Y, and Z
        Console.WriteLine($"Reading: X: {data.MagneticField.X}, Y: {data.MagneticField.Y}, Z: {data.MagneticField.Z}");
    }
 
    public void ToggleMagnetometer()
    {
        try
        {
            if (Magnetometer.IsMonitoring)
              Magnetometer.Stop();
            else
              Magnetometer.Start(speed);
        }
        catch (FeatureNotSupportedException fnsEx)
        {
            // Feature not supported on device
        }
        catch (Exception ex)
        {
            // Other error has occurred.
        }
    }
}
All data is returned in microteslas.

Sensor Speed

  • Fastest – Get the sensor data as fast as possible (not guaranteed to return on UI thread).
  • Game – Rate suitable for games (not guaranteed to return on UI thread).
  • Normal – Default rate suitable for screen orientation changes.
  • Ui – Rate suitable for general user interface.

 

 

Xamarin.Essentials Browser

The Browser class enables an application to open a web link in the optimized system preferred browser or the external browser.

Using Browser

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
The Browser functionality works by calling the OpenAsync method with the Uri and BrowserLaunchType.
C#
 
public class BrowserTest
{
    public async Task OpenBrowser(Uri uri)
    {
        await Browser.RequestAsync(uri, BrowserLaunchType.SystemPreferred);
    }
}

Platform Implementation Specifics

The Launch Type determines how the browser is launched:

System Preferred

Chrome Custom Tabs will attempted to be used load the Uri and keep navigation awareness.
https://developer.chrome.com/multidevice/android/customtabs


External

An Intent will be used to request the Uri be opened through the systems normal browser.
IOS

System Preferred

SFSafariViewController is used to to load the Uri and keep navigation awareness.

External

The standard OpenUrl on the main application is used to launch the default browser outside of the application.
https://developer.xamarin.com/api/type/SafariServices.SFSafariViewController/
UWP: The user's default browser will always be launched regardless of the BrowserLaunchType.

Xamarin.Essentials Phone Dialer

The PhoneDialer class enables an application to open a web link in the optimized system preferred browser or the external browser.

Using Phone Dialer

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
The Phone Dialer functionality works by calling the Open method with a phone number to open the dialer with. When Open is requested the API will automatically attempt to format the number based on the country code if specified.
C#
public class PhoneDialerTest
{
    public async Task PlacePhoneCall(string number)
    {
        try
        {
            PhoneDialer.Open(number);
        }
        catch (ArgumentNullException anEx)
        {
            // Number was null or white space
        }
        catch (FeatureNotSupportedException ex)
        {
            // Phone Dialer is not supported on this device.
        }
        catch (Exception ex)
        {
            // Other error has occurred.
        }
    }
}

Xamarin.Essentials Preferences

The Preferences class helps to store application preferences in a key/value store.

Using Secure Storage

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
To save a value for a given key in preferences:
C#
Preferences.Set("my_key", "my_value");
To retrieve a value from preferences or a default if not set:
C#
var myValue = Preferences.Get("my_key", "default_value");
To remove the key from preferences:
C#
Preferences.Remove("my_key");
To remove all preferences:
C#
Preferences.Clear();
In addition to these methods each take in an optional sharedName that can be used to create additional containers for preference. Read the platform implementation specifics below.

Supported Data Types

The following data types are supported in Preferences:
  • bool
  • double
  • int
  • float
  • long
  • string
Android : All data is stored into Shared Preferences. If no sharedName is specified the default shared preferences are used, else the name is used to get a private shared preferences with the specified name.
https://developer.android.com/training/data-storage/shared-preferences

IOS : NSUserDefaults is used to store values on iOS devices. If no sharedName is specified the StandardUserDefaults are used, else the name is used to create a new NSUserDefaults with the specified name used for the NSUserDefaultsType.SuiteName.
https://docs.microsoft.com/en-us/xamarin/ios/app-fundamentals/user-defaults

UWP : ApplicationDataContainer is used to store the values on the device. If no sharedName is specified the LocalSettings are used, else the name is used to create a new container inside of LocalSettings.
https://docs.microsoft.com/en-us/uwp/api/windows.storage.applicationdatacontainer

Xamarin.Essentials Screen Lock

The ScreenLock class can request to keep the screen from falling asleep when the application is running.

Using ScreenLock

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
The screen lock functionality works by calling the RequestActive and RequestRelease methods to request the screen from turning off.
C#
public class ScreenLockTest
{
    public void ToggleScreenLock()
    {
        if (ScreenLock.IsMonitoring)
            ScreenLock.RequestActive();
        else
            ScreenLock.RequestRelease;
    }
}

Xamarin.Essentials Secure Storage

The SecureStorage class helps securely store simple key/value pairs.

Using Secure Storage

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
To save a value for a given key in secure storage:
C#
await SecureStorage.SetAsync("oauth_token", "secret-oauth-token-value");
To retrieve a value from secure storage:
C#
var oauthToken = await SecureStorage.GetAsync("oauth_token");
Android :
The Android KeyStore is used to store the cipher key used to encrypt the value before it is saved into a Shared Preferences with a filename of [YOUR-APP-PACKAGE-ID].xamarinessentials. The key used in the shared preferences file is a MD5 Hash of the key passed into the SecureStorage API's.

API Level 23 and Higher

On newer API levels, an AES key is obtained from the Android KeyStore and used with an AES/GCM/NoPadding cipher to encrypt the value before it is stored in the shared preferences file.

API Level 22 and Lower

On older API levels, the Android KeyStore only supports storing RSA keys, which is used with an RSA/ECB/PKCS1Padding cipher to encrypt an AES key (randomly generated at runtime) and stored in the shared preferences file under the key SecureStorageKey, if one has not already been generated.
All encrypted values will be removed when the app is uninstalled from the device.
https://developer.android.com/training/articles/keystore
IOS :
KeyChain is used to store values securely on iOS devices. The SecRecord used to store the value has a Service value set to [YOUR-APP-BUNDLE-ID].xamarinessentials.
In some cases KeyChain data is synchronized with iCloud, and uninstalling the application may not remove the secure values from iCloud and other devices of the user.
UWP :
DataProtectionProvider is used to encryped values securely on UWP devices.
Encryped values are stored in ApplicationData.Current.LocalSettings, inside a container with a name of [YOUR-APP-ID].xamarinessentials.
Uninstalling the application will cause the LocalSettings, and all encrypted values to be removed as well.
https://docs.microsoft.com/en-us/uwp/api/windows.security.cryptography.dataprotection.dataprotectionprovider



Xamarin.Essentials SMS

The Sms class enables an application to open the default SMS application with a specified message to send to a recipient.

Using Sms

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
The SMS functionality works by calling the ComposeAsync method an SmsMessage that contains the message's recipient and the body of the message, both of which are optional.
C#
public class SmsTest
{
    public async Task SendSms(string messageText, string recipient)
    {
        try
        {
            var message = new SmsMessage(messageText, recipient);
            await Sms.ComposeAsync(message);
        }
        catch (FeatureNotSupportedException ex)
        {
            // Sms is not supported on this device.
        }
        catch (Exception ex)
        {
            // Other error has occurred.
        }
    }
}

Xamarin.Essentials Text-to-Speech

he TextToSpeech class enables an application utilize the built in text-to-speech engines to speak back text from the device and also to query available languages that the engine can support.

Using Text-to-Speech

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
The Text-to-Speech functionality works by calling the SpeakAsync method with text and optional parameters and returns after the utterance has finished.
C#
public async Task SpeakNowDefaultSettings()
{
    await TextToSpeech.SpeakAsync("Hello World");
 
    // This method will block until utterance finishes.
}
 
public void SpeakNowDefaultSettings2()
{
    TextToSpeech.SpeakAsync("Hello World").ContinueWith((t) => 
    {
        // Logic that will run after utterance finishes.
 
    }, TaskScheduler.FromCurrentSynchronizationContext());
}
This method takes in an optional CancellationToken to stop the utterance one it starts.
C#
CancellationTokenSource cts;
public async Task SpeakNowDefaultSettings()
{
    cts = new CancellationTokenSource();
    await TextToSpeech.SpeakAsync("Hello World", cancelToken: cts.Token);
 
    // This method will block until utterance finishes.
}
 
public void CancelSpeech()
{
    if (cts?.IsCancellationRequested ?? false)
        return;
 
    cts.Cancel();
}
Text-to-Speech will automatically queue speach requests from the same thread.
C#
bool isBusy = false;
public void SpeakMultiple()
{
    isBusy = true;
    Task.Run(async () =>
    {
        await TextToSpeech.SpeakAsync("Hello World 1");
        await TextToSpeech.SpeakAsync("Hello World 2");
        await TextToSpeech.SpeakAsync("Hello World 3");
        isBusy = false;
    });
 
    // or you can query multiple without a Task:
    Task.WhenAll(
        TextToSpeech.SpeakAsync("Hello World 1"),
        TextToSpeech.SpeakAsync("Hello World 2"),
        TextToSpeech.SpeakAsync("Hello World 3"))
        .ContinueWith((t) => { isBusy = false; }, TaskScheduler.FromCurrentSynchronizationContext());
}

Speech Settings

For more control over how the audio is spoken back with SpeakSettings that allows setting the Volume, Pitch, and Locale.
C#
public async Task SpeakNow()
{
    var settings = new SpeakSettings()
        {
            Volume = .75,
            Pitch = 1.0
        };
 
    await TextToSpeech.SpeakAsync("Hello World", settings);
}
The following are supported values for these parameters:
Parameter
Minimum
Maximum
Pitch
0
2.0
Volume
0
1.0

Speech Locales

Each platform offers locales to speak back text in multiple languages and accents. Each platform has a different codes and ways of specifying this, which is why Essentials provides a cross-platform Locale class and a way to query them with GetLocalesAsync.
C#
public async Task SpeakNow()
{
    var locales = await TextToSpeech.GetLocalesAsync();
 
    // Grab the first locale
    var locale = locales.FirstOrDefault();
 
    var settings = new SpeakSettings()
        {
            Volume = .75,
            Pitch = 1.0,
            Locale = locale
        };
 
    await TextToSpeech.SpeakAsync("Hello World", settings);
}

Limitations

  • Utterance queue is not guaranteed if called across multiple threads.
  • Background audio playback is not officially supported.

 

Xamarin.Essentials Vibration

The Vibration class lets you start and stop the vibrate functionality for a desired amount of time.

Getting Started

To access the Vibration functionality the following platform specific setup is required.
The Vibrate permission is required and must be configured in the Android project. This can be added in the following ways:
Open the AssemblyInfo.cs file under the Properties folder and add:
C#
[assembly: UsesPermission(Android.Manifest.Permission.Vibrate)]
OR Update Android Manifest:
Open the AndroidManifest.xml file under the Properties folder and add the following inside of the manifest node.
XML
<uses-permission android:name="android.permission.VIBRATE" />
Or right click on the Anroid project and open the project's properties. Under Android Manifest find the Required permissions: area and check the VIBRATE permission. This will automatically update the AndroidManifest.xml file.

Using Vibration

Add a reference to Xamarin.Essentials in your class:
C#
using Xamarin.Essentials;
The Vibration functionality can be requested for a set amount of time or the default of 500 milliseconds.
C#
try
{
    // Use default vibration length
    Vibration.Vibrate();
 
    // Or use specified time
    var duration = TimeSpan.FromSeconds(1);
    Vibration.Vibrate(duration);
}
catch (FeatureNotSupportedException ex)
{
    // Feature not supported on device
}
catch (Exception ex)
{
    // Other error has occurred.
}
Cancellation of device vibration can be requested with the Cancel method:
C#
try
{
    Vibration.Cancel();
}
catch (FeatureNotSupportedException ex)
{
    // Feature not supported on device
}
catch (Exception ex)
{
    // Other error has occurred.
}

Platform Differences

Platform
Difference
iOS
Always vibrates for 500 milliseconds.
iOS
Not possible to cancel vibration.
IOS and UWP: No additional setup required.

1 comment:

  1. Nice blog! I really loved reading through this Blog... Thanks for sharing such a very interesting post with us and keep blogging.
    Visit our website-
    hire xamarin developer
    web development company
    android development company

    ReplyDelete