鸿蒙如何实现短时震动

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

json 复制代码
  "requestPermissions": [
      {"name": "ohos.permission.VIBRATE"}
    ],

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

typescript 复制代码
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
ts 复制代码
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}`
      );
    });
}
实战案例
ts 复制代码
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()
      })
    }
  }
}
关于

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

相关推荐
aqi007 小时前
鸿蒙版本的电子书阅读APP开放源码啦
android·华为·ai编程·harmonyos·鸿蒙
xq952711 小时前
HDC Assistant 插件横空出世
harmonyos
垆边人似月.12 小时前
华为机试题 :两数之和
c++·算法·华为
垆边人似月.12 小时前
华为机试题 :有效的括号
c++·算法·华为
高德开放平台15 小时前
高德开放平台×华为:一句话,开启腕上打车
华为
垆边人似月.16 小时前
华为机试题 :字符串压缩
算法·华为
OH_TPC18 小时前
【鸿蒙优选三方库】@ohos/aki:一行代码让 ArkTS 调 C++
harmonyos
垆边人似月.19 小时前
华为机试题 :最长递增子序列题目
数据结构·c++·算法·华为
wenyiyiyiyiyi19 小时前
我用鸿蒙 ArkTS 写了个自己天天用的备忘录:待办、课表和长期目标,全塞进一块桌面卡片
harmonyos
承渊政道21 小时前
鸿蒙设备远控电脑实测:ToDesk蓝牙键鼠、双模式鼠标、跨端剪贴板,远控电脑更顺手了
计算机外设·电脑·harmonyos·远程工作·todesk