首先需要在 module.json5 申请权限

  "requestPermissions": [
      {"name": "ohos.permission.VIBRATE"}
    ],

vibrator.startVibration 开启震动
vibrator.stopVibration 停止震动

vibrator.startVibration(
  {
    type: "preset", //类型为预制震动
    effectId: vibrator.HapticFeedback.EFFECT_SHARP, // effectId 为vibrator.HapticFeedback的枚举值
  },
  {
    usage: "unknown", //使用场景 不同的场景会出现不同的震动效果

    //unknown'字符串。受触感开关管控,关闭时不振动。
    //若为'alarm'字符串。受三态开关管控,静音时不振动
  }
);

// vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET为清除预制震动
vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET);
封装震动 vibratorUtil
import { vibrator } from "@kit.SensorServiceKit";
import { hilog } from "@kit.PerformanceAnalysisKit";

export function MyVibrator(count: number) {
  vibrator
    .startVibration(
      {
        type: "preset",
        effectId: vibrator.HapticFeedback.EFFECT_SHARP,
        count: count,
      },
      {
        usage: "unknown",
      }
    )
    .catch((error: BusinessError) => {
      hilog.error(
        0x00001,
        "[vibrator start error]",
        `errCode:${error.code} errMessage:${error.message}`
      );
    });
}

export function stopMyVibrator() {
  vibrator
    .stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET)
    .catch((error: BusinessError) => {
      hilog.error(
        0x00001,
        "[vibrator stop error]",
        `errCode:${error.code} errMessage:${error.message}`
      );
    });
}
实战案例
import { vibrator } from '@kit.SensorServiceKit'
import { MyVibrator, stopMyVibrator } from '../util/vibratorUtil'

@Entry
@Component
struct Index {
  build() {
    Column() {
      Button("vibrate")
        .onClick((event: ClickEvent) => {
          MyVibrator(100)
        })

      Button("stop")
        .onClick((event: ClickEvent) => {
          stopMyVibrator()
      })
    }
  }
}
关于

关于更多参考和资料可以查阅官方文档,本文章仅实现部分功能演示

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐