vibrator-guidelines.md 11.7 KB
Newer Older
G
ge-yafang 已提交
1 2 3 4 5
# Vibrator Development


## When to Use

W
wusongqing 已提交
6
You can set different vibration effects as needed, for example, customizing the vibration intensity, frequency, and duration for button touches, alarm clocks, and incoming calls.
G
ge-yafang 已提交
7

W
wusongqing 已提交
8 9
For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md).

G
ge-yafang 已提交
10 11 12

## Available APIs

G
gloria 已提交
13 14 15 16 17 18
| Module         | API                                                      | Description                                                        |
| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| ohos.vibrator | startVibration(effect: VibrateEffect, attribute: VibrateAttribute): Promise<void> | Starts vibration with the specified effect and attribute. This API uses a promise to return the result.|
| ohos.vibrator | startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback<void>): void | Starts vibration with the specified effect and attribute. This API uses an asynchronous callback to return the result.|
| ohos.vibrator | stopVibration(stopMode: VibratorStopMode): Promise<void> | Stops vibration in the specified mode. This API uses a promise to return the result.                                |
| ohos.vibrator | stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback<void>): void | Stops vibration in the specified mode. This API uses an asynchronous callback to return the result.                                |
G
Gloria 已提交
19 20
| ohos.vibrator | stopVibration(): Promise<void>                         | Stops vibration in all modes. This API uses a promise to return the result.                                    |
| ohos.vibrator | stopVibration(callback: AsyncCallback<void>): void     | Stops vibration in all modes. This API uses an asynchronous callback to return the result.                                    |
G
Gloria 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| ohos.vibrator | isSupportEffect(effectId: string): Promise<boolean>    | Checks whether the passed effect ID is supported. This API uses a promise to return the result. The value **true** means that the passed effect ID is supported, and **false** means the opposite.|
| ohos.vibrator | isSupportEffect(effectId: string, callback: AsyncCallback<boolean>): void | Checks whether the passed effect ID is supported. This API uses an asynchronous callback to return the result. The value **true** means that the passed effect ID is supported, and **false** means the opposite.|


## Custom Vibration Format

Custom vibration enables you to design desired vibration effects by customizing a vibration configuration file and orchestrating vibration forms based on the corresponding rules.

The custom vibration configuration file is in JSON format. An example file is as follows:

```json
{
    "MetaData": {
        "Create": "2023-01-09",
        "Description": "a haptic case",
        "Version": 1.0,
        "ChannelNumber": 1
    },
    "Channels": [
        {
            "Parameters": {
                "Index": 1
            },
            "Pattern": [
                {
                    "Event": {
                        "Type": "transient",
                        "StartTime": 0,
                        "Parameters": {
                            "Intensity": 100,
                            "Frequency": 31
                        }
                    }
                },
                {
                    "Event": {
                        "Type": "continuous",
                        "StartTime": 100,
                        "Duration": 54,
                        "Parameters": {
                            "Intensity": 38,
                            "Frequency": 30
                        }
                    }
                }
            ]
        }
    ]
}
```

This JSON file contains two attributes: **MetaData** and **Channels**.
- **MetaData** contains information about the file header. You can add the following attributes under **MetaData**:
  - **Version**: version number of the file format, which is forward compatible. Currently, only version 1.0 is supported. This parameter is mandatory.
  - **ChannelNumber**: number of channels for vibration. Currently, only one channel is supported, and the value is fixed at **1**. This parameter is mandatory.
  - **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.
- **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.
  - **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:
81 82
- **transient**: short vibration
    - **continuous**: long vibration
G
Gloria 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

The table below describes the parameters under **Event**.

| Parameter| Description| Value or Value Range|
| --- | ------------------------ | ---|
| Type | Type of the vibration event. This parameter is mandatory.| **transient** or **continuous**|
| 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|
| 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|

The following requirements must be met:

| Item| Description                |
| -------- | ------------------------ |
| Number of vibration events| No more than 128|
| Length of the vibration configuration file| Not greater than 64 KB|
G
ge-yafang 已提交
100 101 102 103


## How to Develop

G
Gloria 已提交
104
1. Before using the vibrator on a device, you must declare the **ohos.permission.VIBRATE** permission. For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md).
G
ge-yafang 已提交
105

G
gloria 已提交
106
2. Start vibration with the specified effect and attribute.
W
wusongqing 已提交
107

108
   ```ts
G
gloria 已提交
109
   import vibrator from '@ohos.vibrator';
110
   
G
gloria 已提交
111
   try {
112 113 114 115 116 117 118 119 120 121 122 123 124
     vibrator.startVibration({ // To use startVibration, you must configure the ohos.permission.VIBRATE permission.
       type: 'time',
       duration: 1000,
     }, {
       id: 0,
       usage: 'alarm'
     }, (error) => {
       if (error) {
         console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`);
         return;
       }
       console.info('Succeed in starting vibration.');
     });
G
gloria 已提交
125
   } catch (err) {
126
     console.error(`An unexpected error occurred. Code: ${err.code}, message: ${err.message}`);
G
gloria 已提交
127
   }
G
ge-yafang 已提交
128 129
   ```

G
gloria 已提交
130
3. Stop vibration in the specified mode.
W
wusongqing 已提交
131

132
   ```ts
G
gloria 已提交
133
   import vibrator from '@ohos.vibrator';
134
   
G
gloria 已提交
135
   try {
136 137 138 139 140 141 142 143
     // Stop vibration in VIBRATOR_STOP_MODE_TIME mode. To use stopVibration, you must configure the ohos.permission.VIBRATE permission.
     vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, function (error) {
       if (error) {
         console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`);
         return;
       }
       console.info('Succeeded in stopping vibration.');
     })
G
gloria 已提交
144
   } catch (err) {
145
     console.error(`An unexpected error occurred. Code: ${err.code}, message: ${err.message}`);
G
gloria 已提交
146
   }
G
ge-yafang 已提交
147
   ```
G
Gloria 已提交
148

G
Gloria 已提交
149 150
4. Stop vibration in all modes.

151
   ```ts
G
Gloria 已提交
152 153 154
   import vibrator from '@ohos.vibrator';
   // To use startVibration and stopVibration, you must configure the ohos.permission.VIBRATE permission.
   try {
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
     vibrator.startVibration({
       type: 'time',
       duration: 1000,
     }, {
       id: 0,
       usage: 'alarm'
     }, (error) => {
       if (error) {
         console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`);
         return;
       }
       console.info('Succeed in starting vibration');
     });
     // Stop vibration in all modes.
     vibrator.stopVibration(function (error) {
       if (error) {
         console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`);
         return;
       }
       console.info('Succeed in stopping vibration');
     })
G
Gloria 已提交
176
   } catch (error) {
177
     console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`);
G
Gloria 已提交
178 179 180 181 182
   }
   ```

5. Check whether the passed effect ID is supported.

183
   ```ts
G
Gloria 已提交
184
   import vibrator from '@ohos.vibrator';
185
   
G
Gloria 已提交
186
   try {
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
     // Check whether 'haptic.clock.timer' is supported.
     vibrator.isSupportEffect('haptic.clock.timer', function (err, state) {
       if (err) {
         console.error(`Failed to query effect. Code: ${err.code}, message: ${err.message}`);
         return;
       }
       console.info('Succeed in querying effect');
       if (state) {
         try {
           vibrator.startVibration({ // To use startVibration, you must configure the ohos.permission.VIBRATE permission.
             type: 'preset',
             effectId: 'haptic.clock.timer',
             count: 1,
           }, {
             usage: 'unknown'
           }, (error) => {
             if (error) {
               console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`);
             } else {
               console.info('Succeed in starting vibration');
             }
           });
         } catch (error) {
           console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`);
         }
       }
     })
G
Gloria 已提交
214
   } catch (error) {
215
     console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`);
G
Gloria 已提交
216 217
   }
   ```
G
Gloria 已提交
218 219 220

6. Start and stop custom vibration.

221
   ```ts
G
Gloria 已提交
222 223 224 225 226
   import vibrator from '@ohos.vibrator';
   
   const FILE_NAME = "xxx.json";
   
   // Obtain the file descriptor of the vibration configuration file.
227 228 229 230 231 232 233
   let fileDescriptor = undefined;
   getContext().resourceManager.getRawFd(FILE_NAME).then(value => {
     fileDescriptor = { fd: value.fd, offset: value.offset, length: value.length };
     console.info('Succeed in getting resource file descriptor');
   }).catch(error => {
     console.error(`Failed to get resource file descriptor. Code: ${error.code}, message: ${error.message}`);
   });
G
Gloria 已提交
234 235
   // To use startVibration and stopVibration, you must configure the ohos.permission.VIBRATE permission.
   try {
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
     // Start custom vibration.
     vibrator.startVibration({
       type: "file",
       hapticFd: { fd: fileDescriptor.fd, offset: fileDescriptor.offset, length: fileDescriptor.length }
     }, {
       usage: "alarm"
     }).then(() => {
       console.info('Succeed in starting vibration');
     }, (error) => {
       console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`);
     });
     // Stop vibration in all modes.
     vibrator.stopVibration(function (error) {
       if (error) {
         console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`);
         return;
       }
       console.info('Succeed in stopping vibration');
     })
G
Gloria 已提交
255
   } catch (error) {
256
     console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`);
G
Gloria 已提交
257
   }
258 259 260 261 262 263
   // 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}`);
   });
G
Gloria 已提交
264 265
   ```