Using Xamarin.Essentials Accelerometer in Xamarin.Forms: A Practical Guide
Learn how to add Xamarin.Essentials Accelerometer to a Xamarin.Forms app, handle permissions, detect missing sensors, and use a DependencyService fallback. Validate the implementation on real devices and ensure battery‑efficient lifecycle management.
06 Nov 2025, 12:12 UTC

Problem Statement
You want to read real‑time accelerometer data in a Xamarin.Forms app, but you need a reliable, battery‑efficient, and cross‑platform solution that works on Android, iOS, and macOS. Xamarin.Essentials offers a unified API, yet developers often stumble over permission handling, sensor support checks, and lifecycle management. This guide shows how to implement Accelerometer support, validate it on real devices, and fall back gracefully when the native sensor is unavailable.
Desired Outcome
By the end of this article you will have a working Xamarin.Forms page that:
- Starts the accelerometer when the page appears and stops it when it disappears.
- Requests the necessary permissions automatically and handles permission denials.
- Detects when the device lacks an accelerometer and switches to a custom DependencyService fallback.
- Logs sensor values and shows a user‑friendly message if the sensor cannot be used.
Prerequisites
- Xamarin.Forms project targeting .NET 6 (or later) and Xamarin.Essentials 1.7+.
- Android SDK 21+ and iOS deployment target 11.0+.
- Physical Android or iOS device (emulators can be used but may lack hardware sensors).
- NuGet package manager or dotnet CLI.
Step‑by‑Step Implementation
1. Add Xamarin.Essentials to the Project
dotnet add package Xamarin.Essentials
Run dotnet restore and rebuild the solution. The package is referenced in the shared project and each platform project automatically.
2. Configure Platform‑Specific Permissions
For Android add the following to AndroidManifest.xml (inside the <manifest> tag):
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
For iOS add the key NSMotionUsageDescription to Info.plist with a user‑visible description.
3. Create the Accelerometer Page
In the shared project add AccelerometerPage.xaml and its code‑behind.
using Xamarin.Essentials;
using Xamarin.Forms;
namespace YourApp.Pages
{
public partial class AccelerometerPage : ContentPage
{
public AccelerometerPage()
{
InitializeComponent();
AccelerometerStatusLabel.Text = "Waiting for sensor…";
}
protected override void OnAppearing()
{
base.OnAppearing();
StartAccelerometer();
}
protected override void OnDisappearing()
{
StopAccelerometer();
base.OnDisappearing();
}
void StartAccelerometer()
{
try
{
Accelerometer.ReadingChanged += Accelerometer_ReadingChanged;
Accelerometer.Start(SensorSpeed.UI);
}
catch (FeatureNotSupportedException)
{
// No native sensor – fall back to custom service
var fallback = DependencyService.Get();
if (fallback != null)
{
fallback.Start();
}
else
{
AccelerometerStatusLabel.Text = "Accelerometer not available.";
}
}
catch (PermissionException)
{
AccelerometerStatusLabel.Text = "Permission denied. Please enable Motion access.";
}
}
void StopAccelerometer()
{
Accelerometer.ReadingChanged -= Accelerometer_ReadingChanged;
Accelerometer.Stop();
var fallback = DependencyService.Get();
fallback?.Stop();
}
void Accelerometer_ReadingChanged(object sender, AccelerometerChangedEventArgs e)
{
Device.BeginInvokeOnMainThread(() =>
{
AccelerometerStatusLabel.Text = $"X: {e.Reading.AccelerationX:F2}, Y: {e.Reading.AccelerationY:F2}, Z: {e.Reading.AccelerationZ:F2}";
});
}
}
}
4. Define a Fallback Interface
If the device lacks a built‑in sensor, you can provide a platform‑specific fallback using Xamarin’s DependencyService:
public interface IAccelerometerService
{
void Start();
void Stop();
}
Implement IAccelerometerService in each platform project (e.g., a mock or a software‑defined simulation). Register the implementation with DependencyService.Register<IAccelerometerService, PlatformAccelerometerService>(); in the platform’s AppDelegate.cs or MainActivity.cs.
5. Validate Sensor Output
Once deployed to a real device, navigate to AccelerometerPage. The label should update at ~10 Hz. Verify that:
- The app requests motion permission only once.
- Disabling the sensor (e.g., turning off motion in the device settings) triggers
FeatureNotSupportedExceptionand displays the fallback message. - When the page is hidden, the accelerometer stops and battery usage drops.
Expected Checks and Diagnostics
- Permission Status: Use
Permissions.CheckStatusAsync<Permissions.Movement>()to confirm permission before starting the sensor. - Feature Support: Catch
FeatureNotSupportedExceptionto detect missing hardware. - Lifecycle: Ensure
Accelerometer.Stop()is called inOnDisappearingto avoid background leaks. - Logcat / Console: Verify that permission prompts appear only when necessary and that sensor values are logged.
Recovery Options
If the user denies motion permission, show a dialog explaining why the feature is needed and offer to open the device settings. If the hardware is missing, the fallback service can provide simulated data or a graceful degradation message.
Limitations and Caveats
- Android 13+ requires
android.permission.ACTIVITY_RECOGNITIONfor background sensor access; foreground usage is unaffected. - The
AccelerometerAPI is available only on devices that expose the sensor; emulators may not simulate it. - Battery drain can still occur if the sensor is left running; always stop it in
OnDisappearing.
Practical Verification Checklist
- Build and deploy to a physical device.
- Navigate to the accelerometer page and observe the live data.
- Disable motion permission in the device settings and re‑open the page; ensure the fallback message appears.
- Use a device without an accelerometer (or an emulator lacking the sensor) to confirm graceful handling.
- Check battery statistics to verify the sensor stops when the page is hidden.
Conclusion
With Xamarin.Essentials you can expose a consistent accelerometer API across platforms, handle permissions automatically, and provide a robust fallback strategy. Following the lifecycle best practices and validating on real hardware guarantees a smooth user experience and efficient battery usage.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.