Listening for sensor triggers

Some sensors do not provide a continuous stream of data, but rather raise an event when something happens.

How to do it...

To use trigger-based sensors, we also make use of the sensor manager. Unlike stream-based sensors, we inherit from the TriggerEventListener type:

  1. First, we need the instance of the SensorManager type:
    var manager = SensorManager.FromContext(this);
  2. Next, we get a reference to the sensor. If the sensor is null, then it is not available on the device:
    var type = SensorType.SignificantMotion;
    var motion = manager.GetDefaultSensor(type);
    if (motion == null) {
      // handle no significant motion sensor
    }
  3. Then, we create inherit from the TriggerEventListener type:
    private class MyListener : TriggerEventListener ...

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.