Xamarin.Forms - Turn ON/Off Flashlight Using Xamarin Essentials

Introduction
Xamarin

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.

Xamarin.Essentials
Xamarin
 
The Xamarin.Essentials plugin provides 20+ cross-platform APIs for mobile application development. Xamarin.Essentials API works with all Xamarin.Forms, Xamarin.Android, Xamarin.iOS, or UWP applications that can be accessed from shared code. Developers can now access every native platform API using C#. This plugin provides many APIs so initially, there is no need of more plugins for Xamarin. Xamarin.Essentials plugin impacts your app's minimum size.

Platform Support
 
Xamarin.Essentials supports various platforms and operating systems
 
 PlatformVersion 
 Android 4.4 (API 19) or earlier
 iOS 10.0 or higher
 UWP 10.0.16299.0 or earlier
 
Prerequisites
  • Visual Studio 2017(Windows or Mac)
Setting up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You’ll learn more by going through the steps yourself. Choose the Xamarin.Forms App Project type under Cross-platform/App in the New Project dialog.

Xamarin 
 
Name your app, select “Use Portable Class Library” for shared code, and target both - Android and iOS.

Xamarin 

You probably want your project and solution to use the same name as your app. Put it in your preferred folder for projects and click "Create".

Xamarin 

You now have a basic Xamarin.Forms app. Click the Play button to try it out.

Xamarin 

Setting up the User Interface

Go to MainPage.Xaml and write the following code.
 
MainPage.xaml
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              xmlns:local="clr-namespace:XamarinEssentials"  
  5.              x:Class="XamarinEssentials.MainPage">  
  6.   
  7.     <StackLayout>  
  8.         <StackLayout HorizontalOptions="Center" VerticalOptions="Start">  
  9.   
  10.          <Image Margin="0,50,0,0" x:Name="imgBanner" Source="banner.png" ></Image>  
  11.          <Image Margin="0,0,0,10" x:Name="imgXamarinEssential" Source="xamarinessential.png" ></Image>  
  12.          <Label Margin="0,0,0,10" FontAttributes="Bold" FontSize="Large" TextColor="#CA6F1E" HorizontalTextAlignment="Center" Text="Appinfo"></Label>  
  13.            <Button Text="Flash on" Clicked="Handle_Clicked"></Button>  
  14.            <Button Text="Flash off" Clicked="Handle_Clicked_1"></Button>  
  15.          </StackLayout>  
  16.     </StackLayout>  
  17.   
  18. </ContentPage>  
Add Xamarin Essentials
 
In this step, add Xamarin.Essentials to your project. You can install Xamarin.Essentials via NuGet, or you can browse the source code on GitHub.

Go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for Solution". Search "Xamarin.Essentials" and add Package. Remember to install it for each project (PCL, Android, iO, and UWP).

Xamarin

Xamarin.Essentials requires platform-specific setup - 
Android

The following steps are necessary for Android.
  1. Xamarin.Essentials supports a minimum Android version of 4.4
  2. Target Android version for compiling must be 8.1, API level 27.
In the Android project's MainActivity that is launched Xamarin.Essentials must be initialized in the OnCreate method.

MainActivity.cs
  1. Xamarin.Essentials.Platform.Init(this, bundle);  
Xamarin.Essentials must receive any OnRequestPermissionsResult. write the following code for runtime permission.

MainActivity.cs
  1. public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)  
  2. {  
  3.     Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);  
  4.   
  5.     base.OnRequestPermissionsResult(requestCode, permissions, grantResults);  
  6. }  
iOS

No additional setup required.

UWP

No additional setup required.

Permissions

In this step give the following required permissions to your app:
  1. CAMERA
  2. FLASHLIGHT
Limitation
  • It supports the devices only, not Simulator/Emulator
In this step, write the following code for switching ON the Flashlight.

MainPage.xaml.cs
  1. async void Handle_Clicked(object sender, System.EventArgs e)  
  2.         {  
  3.             try  
  4.             {  
  5.                 // Turn On Flashlight  
  6.                 await Flashlight.TurnOnAsync();  
  7.             }  
  8.             catch (FeatureNotSupportedException fnsEx)  
  9.             {  
  10.                 await ShowAlert(fnsEx.Message);  
  11.             }  
  12.             catch (PermissionException pEx)  
  13.             {  
  14.                 await ShowAlert(pEx.Message);  
  15.             }  
  16.             catch (Exception ex)  
  17.             {  
  18.                 await ShowAlert(ex.Message);  
  19.             }  
  20.         }  
Now, write the following code for switching Off the Flashlight.

MainPage.xaml.cs
  1. async void Handle_Clicked_1(object sender, System.EventArgs e)  
  2.         {  
  3.             try  
  4.             {  
  5.                 // Turn Off Flashlight  
  6.                 await Flashlight.TurnOffAsync();  
  7.             }  
  8.             catch (FeatureNotSupportedException fnsEx)  
  9.             {  
  10.                 await ShowAlert(fnsEx.Message);  
  11.             }  
  12.             catch (PermissionException pEx)  
  13.             {  
  14.                 await ShowAlert(pEx.Message);  
  15.             }  
  16.             catch (Exception ex)  
  17.             {  
  18.                 await ShowAlert(ex.Message);  
  19.             }  
  20.         }  
Full code - MainPage.xaml.cs
  1. using Xamarin.Forms;  
  2. using Xamarin.Essentials;  
  3. namespace XamarinEssentials  
  4. {  
  5.     public partial class MainPage : ContentPage  
  6.     {  
  7.         public MainPage()  
  8.         {  
  9.             InitializeComponent();  
  10.         }  
  11.   
  12.         async void Handle_Clicked(object sender, System.EventArgs e)  
  13.         {  
  14.             try  
  15.             {  
  16.                 // Turn On Flashlight  
  17.                 await Flashlight.TurnOnAsync();  
  18.             }  
  19.             catch (FeatureNotSupportedException fnsEx)  
  20.             {  
  21.                 await ShowAlert(fnsEx.Message);  
  22.             }  
  23.             catch (PermissionException pEx)  
  24.             {  
  25.                 await ShowAlert(pEx.Message);  
  26.             }  
  27.             catch (Exception ex)  
  28.             {  
  29.                 await ShowAlert(ex.Message);  
  30.             }  
  31.         }  
  32.   
  33.         async void Handle_Clicked_1(object sender, System.EventArgs e)  
  34.         {  
  35.             try  
  36.             {  
  37.                 // Turn Off Flashlight  
  38.                 await Flashlight.TurnOffAsync();  
  39.             }  
  40.             catch (FeatureNotSupportedException fnsEx)  
  41.             {  
  42.                 await ShowAlert(fnsEx.Message);  
  43.             }  
  44.             catch (PermissionException pEx)  
  45.             {  
  46.                 await ShowAlert(pEx.Message);  
  47.             }  
  48.             catch (Exception ex)  
  49.             {  
  50.                 await ShowAlert(ex.Message);  
  51.             }  
  52.         }  
  53.   
  54.         public async Task ShowAlert(string message)  
  55.         {  
  56.             await DisplayAlert("Faild", message, "Ok");  
  57.         }  
  58.     }  
  59. }  
Click the Play button to try it out.
 
Xamarin 

Related post
I hope you have understood how to turn the flashlight on or off using Xamarin.Essentials in Xamarin.Forms.
Thanks for reading. Please share comments and feedback.


Similar Articles