未验证 提交 67c79741 编写于 作者: O openharmony_ci 提交者: Gitee

!21908 翻译完成:21038+21114+21212+21053 【泛Sensor】修复文档描述、代码示例

Merge pull request !21908 from wusongqing/TR21038
...@@ -15,65 +15,64 @@ For details about the APIs, see [Sensor](../reference/apis/js-apis-sensor.md). ...@@ -15,65 +15,64 @@ For details about the APIs, see [Sensor](../reference/apis/js-apis-sensor.md).
| ohos.sensor | sensor.on(sensorId, callback:AsyncCallback<Response>): void | Subscribes to data changes of a type of sensor.| | 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.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.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 ## How to Develop
1. Before obtaining data from a type of sensor, check whether the required permission has been configured.<br> The acceleration sensor is used as an example.
The system provides the following sensor-related permissions:
- ohos.permission.ACCELEROMETER
- ohos.permission.GYROSCOPE 1. Import the module.
- ohos.permission.ACTIVITY_MOTION
- ohos.permission.READ_HEALTH_DATA
For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md).
2. Subscribe to data changes of a type of sensor. The following uses the acceleration sensor as an example.
```ts ```ts
import sensor from "@ohos.sensor"; import sensor from "@ohos.sensor";
```
sensor.on(sensor.SensorId.ACCELEROMETER, function (data) { 2. Obtain information about all sensors on the device.
console.info("Succeeded in obtaining data. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
```ts
sensor.getSensorList(function (error, data) {
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]));
}
}
}); });
``` ```
![171e6f30-a8d9-414c-bafa-b430340305fb](figures/171e6f30-a8d9-414c-bafa-b430340305fb.png) ![](figures/001.png)
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.
3. Check whether the corresponding permission has been configured. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md).
3. Unsubscribe from sensor data changes. 4. 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.
```ts ```ts
import sensor from "@ohos.sensor"; sensor.on(sensor.SensorId.ACCELEROMETER, function (data) {
sensor.off(sensor.SensorId.ACCELEROMETER); console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z);
}, {'interval': 100000000});
``` ```
![65d69983-29f6-4381-80a3-f9ef2ec19e53](figures/65d69983-29f6-4381-80a3-f9ef2ec19e53.png) ![](figures/002.png)
4. Subscribe to only one data change of a type of sensor. - The **once()** API is used to listen for only one data change of the sensor.
```ts ```ts
import sensor from "@ohos.sensor";
sensor.once(sensor.SensorId.ACCELEROMETER, function (data) { sensor.once(sensor.SensorId.ACCELEROMETER, function (data) {
console.info("Succeeded in obtaining data. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained. console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z);
}); });
``` ```
![db5d017d-6c1c-4a71-a2dd-f74b7f23239e](figures/db5d017d-6c1c-4a71-a2dd-f74b7f23239e.png) ![](figures/003.png)
If the API fails to be called, you are advised to use the **try/catch** statement to capture error information that may occur in the code. Example: 5. Cancel continuous listening.
```ts ```ts
import sensor from "@ohos.sensor"; sensor.off(sensor.SensorId.ACCELEROMETER);
try {
sensor.once(sensor.SensorId.ACCELEROMETER, function (data) {
console.info("Succeeded in obtaining data. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
});
} catch (error) {
console.error(`Failed to get sensor data. Code: ${error.code}, message: ${error.message}`);
}
``` ```
...@@ -76,9 +76,9 @@ This JSON file contains two attributes: **MetaData** and **Channels**. ...@@ -76,9 +76,9 @@ This JSON file contains two attributes: **MetaData** and **Channels**.
- **Create**: time when the file was created. This parameter is optional. - **Create**: time when the file was created. This parameter is optional.
- **Description**: additional information such as the vibration effect and creation information. This parameter is optional. - **Description**: additional information such as the vibration effect and creation information. This parameter is optional.
- **Channels** provides information about the vibration channel. It is a JSON array that holds information about each channel. It contains two attributes: **Parameters** and **Pattern**. - **Channels** provides information about the vibration channel. It is a JSON array that holds information about each channel. It contains two attributes: **Parameters** and **Pattern**.
- **Parameters** provides parameters related to the channel. Under it, **Index** indicates the channel ID. The value is fixed at **1** for a single channel. This parameter is mandatory. - **Parameters** provides parameters related to the channel. Under it, **Index** indicates the channel ID. The value is fixed at **1** for a single channel. This parameter is mandatory.
- **Pattern** indicates the vibration sequence. It is a JSON array. Under it, **Event** indicates a vibration event, which can be either of the following types: - **Pattern** indicates the vibration sequence. It is a JSON array. Under it, **Event** indicates a vibration event, which can be either of the following types:
- **transient**: short vibration - **transient**: short vibration
- **continuous**: long vibration - **continuous**: long vibration
The table below describes the parameters under **Event**. The table below describes the parameters under **Event**.
...@@ -89,7 +89,7 @@ The table below describes the parameters under **Event**. ...@@ -89,7 +89,7 @@ The table below describes the parameters under **Event**.
| StartTime | Start time of the vibration. This parameter is mandatory.| [0, 1800 000], in ms, without overlapping| | StartTime | Start time of the vibration. This parameter is mandatory.| [0, 1800 000], in ms, without overlapping|
| Duration | Duration of the vibration. This parameter is valid only when **Type** is **continuous**.| (10, 1600), in ms| | Duration | Duration of the vibration. This parameter is valid only when **Type** is **continuous**.| (10, 1600), in ms|
| Intensity | Intensity of the vibration. This parameter is mandatory.| [0, 100], a relative value that does not represent the actual vibration strength.| | Intensity | Intensity of the vibration. This parameter is mandatory.| [0, 100], a relative value that does not represent the actual vibration strength.|
| Frequency | Frequency of the vibration. This parameter is mandatory.| [0, 100], a relative value that does not represent the actual vibration frequency| | Frequency | Frequency of the vibration. This parameter is mandatory.| [0, 100], a relative value that does not represent the actual vibration frequency.|
The following requirements must be met: The following requirements must be met:
...@@ -221,22 +221,24 @@ The following requirements must be met: ...@@ -221,22 +221,24 @@ The following requirements must be met:
```ts ```ts
import vibrator from '@ohos.vibrator'; import vibrator from '@ohos.vibrator';
const FILE_NAME = "xxx.json";
// Obtain the file descriptor of the vibration configuration file. // Obtain the file descriptor of the vibration configuration file.
let fileDescriptor = undefined; async function getRawfileFd(fileName) {
getContext().resourceManager.getRawFd(FILE_NAME).then(value => { let rawFd = await globalThis.getContext().resourceManager.getRawFd(fileName);
fileDescriptor = { fd: value.fd, offset: value.offset, length: value.length }; return rawFd;
console.info('Succeed in getting resource file descriptor'); }
}).catch(error => {
console.error(`Failed to get resource file descriptor. Code: ${error.code}, message: ${error.message}`); // Close the file descriptor of the vibration configuration file.
}); async function closeRawfileFd(fileName) {
// To use startVibration and stopVibration, you must configure the ohos.permission.VIBRATE permission. await globalThis.getContext().resourceManager.closeRawFd(fileName)
}
// Play the custom vibration. To use startVibration and stopVibration, you must configure the ohos.permission.VIBRATE permission.
async function playCustomHaptic(fileName) {
try { try {
// Start custom vibration. let rawFd = await getRawfileFd(fileName);
vibrator.startVibration({ vibrator.startVibration({
type: "file", type: "file",
hapticFd: { fd: fileDescriptor.fd, offset: fileDescriptor.offset, length: fileDescriptor.length } hapticFd: { fd: rawFd.fd, offset: rawFd.offset, length: rawFd.length }
}, { }, {
usage: "alarm" usage: "alarm"
}).then(() => { }).then(() => {
...@@ -244,7 +246,6 @@ The following requirements must be met: ...@@ -244,7 +246,6 @@ The following requirements must be met:
}, (error) => { }, (error) => {
console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`);
}); });
// Stop vibration in all modes.
vibrator.stopVibration(function (error) { vibrator.stopVibration(function (error) {
if (error) { if (error) {
console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`);
...@@ -252,14 +253,10 @@ The following requirements must be met: ...@@ -252,14 +253,10 @@ The following requirements must be met:
} }
console.info('Succeed in stopping vibration'); console.info('Succeed in stopping vibration');
}) })
await closeRawfileFd(fileName);
} catch (error) { } catch (error) {
console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`);
} }
// Close the vibration file. }
getContext().resourceManager.closeRawFd(FILE_NAME).then(() => {
console.info('Succeed in closing resource file descriptor');
}).catch(error => {
console.error(`Failed to close resource file descriptor. Code: ${error.code}, message: ${error.message}`);
});
``` ```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册