Detecting device shakes

A fairly common gesture that can be implemented using sensors is the shake gesture. This can be used to shuffle cards in a game or tracks in a playlist.

How to do it...

To detect a shake, we will need to record the data from the accelerometer and determine whether a shake has occurred:

  1. First, we implement the ISensorEventListener interface, and register it with the manager:
    var manager = SensorManager.FromContext(this);
    var type = SensorType.Accelerometer;
    var accelerometer = manager.GetDefaultSensor(type);
    manager.RegisterListener(
      this, accelerometer, SensorDelay.Fastest);
  2. Then, we will need a few fields that will store the values across the accelerometer events:
    private int lastUpdate; private float lastX; private float lastY; ...

Get Xamarin Mobile Development for Android Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.