鸿蒙如何实现短时震动

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

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

相关推荐
儿歌八万首1 小时前
鸿蒙 ArkUI 实战:沉浸式状态栏的 3 种实现方案
华为·harmonyos
大雷神1 小时前
HarmonyOS中考试模板开发教程
华为·harmonyos
全栈开发圈2 小时前
干货分享|鸿蒙6开发实战指南
人工智能·harmonyos·鸿蒙·鸿蒙系统
鸣弦artha2 小时前
Flutter框架跨平台鸿蒙开发 —— Image Widget 基础:图片加载方式
flutter·华为·harmonyos
奋斗的小青年!!3 小时前
在OpenHarmony上玩转Flutter弹出菜单:我的实战经验分享
flutter·harmonyos·鸿蒙
lili-felicity4 小时前
React Native for OpenHarmony 实战:加载效果的实现详解
javascript·react native·react.js·harmonyos
哈哈你是真的厉害4 小时前
React Native 鸿蒙跨平台开发:BaseConverter 进制转换
react native·react.js·harmonyos
奋斗的小青年!!4 小时前
Flutter跨平台开发:笔记分享功能适配OpenHarmony
flutter·harmonyos·鸿蒙
时光慢煮5 小时前
从踩坑到跑通:uni-app 项目落地 HarmonyOS 的完整实录(含模拟器 / 真机)
华为·uni-app·harmonyos
小雨青年5 小时前
我开发的鸿蒙原生应用【会议随记Pro】上架了
华为·harmonyos