Some sensors do not provide a continuous stream of data, but rather raise an event when something happens.
To use trigger-based sensors, we also make use of the sensor manager. Unlike stream-based sensors, we inherit from the TriggerEventListener
type:
SensorManager
type:var manager = SensorManager.FromContext(this);
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 }
TriggerEventListener
type:private class MyListener : TriggerEventListener { public override void OnTrigger(TriggerEvent e) { // handle significant motion } }
listener = new MyListener();
manager.RequestTriggerSensor(listener, motion);
manager.CancelTriggerSensor(listener, motion);
Devices have many sensors, some providing a stream of data to apps and others providing data when certain events occur. These events might be triggered when the user takes a step or when the user moves to a new location.
These sensors work by only enabling when a listener is attached, then as soon as the event it raised, the trigger is invoked and the listener detached. In order for the trigger to be invoked when the event occurs again, we need to reregister the listener.
Just like when accessing all other sensors, we need to use the SensorManager
instance. Once we have obtained the sensor manager, we need to ensure that the particular sensor exists on the device. As with all sensors, we use the GetDefaultSensor()
method to do this.
Once we have the sensor, we need an instance of the TriggerEventListener
type. Unlike other sensors, this is not an interface to be implemented. Instead, it is a type that we inherit from and override the OnTrigger()
method.
The OnTrigger()
method has a single TriggerEvent
argument, which provides access to the timestamp of the event and the actual sensor data. The sensor data is provided in the form of a float array property named Values
.
When we want to register the listener with the sensor, we pass an instance of the listener and the sensor to the RequestTriggerSensor()
method on the sensor manager. As soon as the event is raised, the OnTrigger()
method will be invoked and the listener automatically unregistered. If the trigger needs to be invoked again, it will have to be reregistered.
Once we no longer need the sensor to invoke our trigger, we can cancel the listener by passing both the listener and the sensor to the CancelTriggerSensor()
method on the sensor manager.