แชร์ผ่าน


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.

Get started

To start using this API, read the getting started guide for Xamarin.Essentials to ensure the library is properly installed and set up in your projects.

Using Gyroscope

Add a reference to Xamarin.Essentials in your class:

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 in rad/s. Here is sample usage:


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(object sender, GyroscopeChangedEventArgs e)
    {
        var data = e.Reading;
        // Process Angular Velocity X, Y, and Z reported in rad/s
        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).
  • Default – Default rate suitable for screen orientation changes.
  • UI – Rate suitable for general user interface.

If your event handler is not guaranteed to run on the UI thread, and if the event handler needs to access user-interface elements, use the MainThread.BeginInvokeOnMainThread method to run that code on the UI thread.

API