目录

Sensor Development

When to Use

When an application needs to obtain sensor data, it can use the sensor module. For example, an application can subscribe to orientation sensor data to detect the current orientation of the user's device.

For details about the APIs, see @ohos.sensor (Sensor).

Available APIs

Module Name Description
ohos.sensor sensor.on(sensorId, callback:AsyncCallback<Response>): void Enables listening for data changes of the specified type of sensor.
ohos.sensor sensor.off(sensorId, callback?:AsyncCallback<void>): void Disables listening for data changes of the specified type of sensor.

How to Develop

The acceleration sensor is used as an example.

  1. Import the required module.

    import sensor from '@ohos.sensor';
  2. Check whether the corresponding permission has been granted.

  3. 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' });

  4. Disable listening for sensor status changes.

    sensor.off(sensor.SensorId.ACCELEROMETER);