Поділитися через


Xamarin.Essentials: Detect Shake

The Accelerometer class lets you monitor the device's accelerometer sensor, which indicates the acceleration of the device in three-dimensional space. Additionally, it enables you to register for events when the user shakes the device.

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 Detect Shake

Add a reference to Xamarin.Essentials in your class:

using Xamarin.Essentials;

To detect a shake of the device you must use the Accelerometer functionality by calling the Start and Stop methods to listen for changes to the acceleration and to detect a shake. Any time a shake is detected a ShakeDetected event will fire. It is recommended to use Game or faster for the SensorSpeed. Here is sample usage:


public class DetectShakeTest
{
    // Set speed delay for monitoring changes.
    SensorSpeed speed = SensorSpeed.Game;

    public DetectShakeTest()
    {
        // Register for reading changes, be sure to unsubscribe when finished
        Accelerometer.ShakeDetected  += Accelerometer_ShakeDetected ;
    }

    void Accelerometer_ShakeDetected (object sender, EventArgs e)
    {
        // Process shake event
    }

    public void ToggleAccelerometer()
    {
        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.
        }
    }
}

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.

Implementation Details

The detect shake API uses raw readings from the accelerometer to calculate acceleration. It uses a simple queue mechanism to detect if 3/4ths of the recent accelerometer events occurred in the last half second. Acceleration is calculated by adding the square of the X, Y, and Z readings from the accelerometer and comparing it to a specific threashold.

API

Find more Xamarin videos on Channel 9 and YouTube.