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:
- 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);
- 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; private float lastZ;
- As we are also going to process shakes, we will need a field to hold the shake related data:
private int lastShake;
- In the
OnSensorChanged()
method, we ensure that we only process the events after a reasonable interval of time...