harmony 鸿蒙Sensor Development
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, and data of the pedometer sensor to learn the number of steps the user walks every day.
For details about the APIs, see Sensor.
Available APIs
Module | API | Description |
---|---|---|
ohos.sensor | sensor.on(sensorId, callback:AsyncCallback<Response>): void | Subscribes to data changes of a type of sensor. |
ohos.sensor | sensor.once(sensorId, callback:AsyncCallback<Response>): void | Subscribes to only one data change of a type of sensor. |
ohos.sensor | sensor.off(sensorId, callback?:AsyncCallback<void>): void | Unsubscribes from sensor data changes. |
ohos.sensor | sensor.getSensorList(callback: AsyncCallback<Array<Sensor>>): void | Obtains information about all sensors on the device. This API uses an asynchronous callback to return the result. |
How to Develop
The acceleration sensor is used as an example.
- Import the module.
import sensor from '@ohos.sensor';
import { BusinessError } from '@ohos.base';
Obtain information about all sensors on the device.
sensor.getSensorList((error: BusinessError, data: Array<sensor.Sensor>) => { if (error) { console.info('getSensorList failed'); } else { console.info('getSensorList success'); for (let i = 0; i < data.length; i++) { console.info(JSON.stringify(data[i])); } } });
The minimum and the maximum sampling periods supported by the sensor are 5000000 ns and 200000000 ns, respectively. Therefore, the value of interval must be within this range.
Check whether the corresponding permission has been configured. For details, see Applying for Permissions.
Register a listener. You can call on() or once() to listen for sensor data changes.
The on() API is used to continuously listen for data changes of the sensor. The sensor reporting interval is set to 100000000 ns.
sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => { console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z); }, { interval: 100000000 });
The once() API is used to listen for only one data change of the sensor.
sensor.once(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => { console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z); });
Cancel continuous listening.
sensor.off(sensor.SensorId.ACCELEROMETER);
你可能感兴趣的鸿蒙文章
harmony 鸿蒙Peripheral Management Development
harmony 鸿蒙Input Device Development
harmony 鸿蒙Location Service Development
harmony 鸿蒙Mouse Pointer Development
harmony 鸿蒙Sample Server Development
harmony 鸿蒙Sample Server Overview
- 所属分类: 后端技术
- 本文标签:
热门推荐
-
2、 - 优质文章
-
3、 gate.io
-
8、 golang
-
9、 openharmony
-
10、 Vue中input框自动聚焦