鸿蒙如何实现短时震动

首先需要在 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()
      })
    }
  }
}
关于

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

相关推荐
OH_TPC24 分钟前
【鸿蒙优选三方库】@ohos/grpc:在 HarmonyOS 上像调本地方法一样调远程服务
华为·harmonyos·鸿蒙
达子66631 分钟前
第30章_综合案例:HarmonyOs开发图解之 俄罗斯方块游戏
游戏·华为·harmonyos
云端漫步198739 分钟前
HarmonyOS NEXT AI 应用开发总结:30 篇之旅
人工智能·华为·harmonyos
math_hongfan1 小时前
鸿蒙Agent高级技能自定义开发:自定义意图服务/能力注册/Agent技能编排/服务插件开发实战
android·学习·华为·harmonyos·鸿蒙
云端漫步19874 小时前
HarmonyOS NEXT AI 智能生活助手:项目打包与发布
人工智能·华为·生活·harmonyos
less_121385 小时前
HarmonyOS WPS Open SDK:关闭回传 URI-FD 与沙箱 filePath
华为·harmonyos·wps
math_hongfan5 小时前
鸿蒙多模态AI交互高级:图文+语音+手势融合交互/多模态大模型端侧适配/跨模态检索高阶实战
人工智能·学习·华为·交互·语音识别·harmonyos·鸿蒙
云端漫步19875 小时前
HarmonyOS NEXT AI 智能生活助手:源码解析与项目复盘
人工智能·华为·生活·harmonyos
math_hongfan5 小时前
鸿蒙AI应用性能高级评测:推理延迟/内存占用/功耗/准确率四维指标评测体系与极致调优方案
人工智能·学习·华为·harmonyos·鸿蒙
less_1213816 小时前
HarmonyOS WPS Open SDK:打开时配置水印与修订模式
华为·harmonyos·wps