Sensor Development
When to Use
With the sensor module, a device can obtain sensor data. For example, the device can subscribe to data of the orientation sensor to detect its own orientation.
For details about the APIs, see Sensor.
Available APIs
| Name | Description |
|---|---|
| sensor.on(sensorId, callback:AsyncCallback<Response>): void | Subscribes to data changes of a type of sensor. |
| sensor.off(sensorId, callback?:AsyncCallback<void>): void | Unsubscribes from sensor data changes. |
How to Develop
The acceleration sensor is used as an example.
-
Import modules.
import { sensor } from '@kit.SensorServiceKit'; -
Check whether the corresponding permission has been configured. For details, see Declaring Permissions.
-
Register a listener.
The on() API is used to continuously listen for data changes of the sensor. The sensor reporting interval is set to game.
sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => { console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z); }, { interval: 'game' });
-
Cancel continuous listening.
sensor.off(sensor.SensorId.ACCELEROMETER);