Xamarin.Essentials Flashlight

Pre-release NuGet

The Flashlight class has the ability to turn on or off the device's camera flash to turn it into a flashlight.

Getting Started

To access the Flashlight functionality the following platform specific setup is required.

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:

[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.

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

[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:

using Xamarin.Essentials;

The flashlight can be turned on and off through the TurnOnAsync and TurnOffAsync methods:

    // 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.