目录

使用Vibrator模块intensity参数调节振幅

问题现象

如何实现设备在不同场景下设置不同的振动效果?例如:设备的按键可以设置不同强度和不同时长的振动。

背景知识

当设备需要设置不同的振动效果时,可以调用@ohos.vibrator的VibratePreset模块,设置振动强度参数intensity调节振幅,详情可参考振动开发指导。

系统支持两种方式调节振动强度:

解决方案

控制设备上的振动器,需要先申请权限ohos.permission.VIBRATE,具体配置方式请参考声明权限。

Usage振动使用场景类型为默认“unknown”时,受系统触感开关管控,关闭时不振动。

可通过如下方案设置振幅,示例代码如下:

import { vibrator } from '@kit.SensorServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct VibratorDemo {
  build() {
    Column() {
      Button('振动')
        .onClick(() => {
          try {
            let ret = vibrator.isHdHapticSupported();
            console.info(`isHdHapticSupported result is ${ret}`);
            if (ret) {
              // 需要在module.json5中添加权限"ohos.permission.VIBRATE"
              vibrator.startVibration({
                type: 'preset',
                count: 20,
                intensity: 100,
                effectId: 'haptic.effect.hard',
              }, {
                // 可定义振动使用场景
                usage: 'unknown'
              }, (error: BusinessError) => {
                if (error) {
                  console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`);
                  return;
                }
                console.info('Succeed in starting vibration');
              });
            } else {
              vibrator.startVibration({
                type: 'preset',
                effectId: 'haptic.effect.soft',
                count: 1,
              }, {
                usage: 'unknown'
              }).then(() => {
                console.info('Succeed in starting vibration');
              }).catch((error: BusinessError) => {
                console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`);
              });
            }
          } catch (err) {
            let e: BusinessError = err as BusinessError;
            console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`);
          }
        });
    }
    .justifyContent(FlexAlign.Center)
    .width('100%').height('100%');
  }
}