鸿蒙如何实现短时震动

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

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

相关推荐
一只大侠的侠36 分钟前
Flutter开源鸿蒙跨平台训练营 Day 10特惠推荐数据的获取与渲染
flutter·开源·harmonyos
御承扬7 小时前
鸿蒙NDK UI之文本自定义样式
ui·华为·harmonyos·鸿蒙ndk ui
前端不太难7 小时前
HarmonyOS 游戏上线前必做的 7 类极端场景测试
游戏·状态模式·harmonyos
大雷神7 小时前
HarmonyOS智慧农业管理应用开发教程--高高种地--第29篇:数据管理与备份
华为·harmonyos
讯方洋哥8 小时前
HarmonyOS App开发——关系型数据库应用App开发
数据库·harmonyos
巴德鸟9 小时前
华为手机鸿蒙4回退到鸿蒙3到鸿蒙2再回退到EMUI11 最后关闭系统更新
华为·智能手机·harmonyos·降级·升级·回退·emui
一起养小猫9 小时前
Flutter for OpenHarmony 实战_魔方应用UI设计与交互优化
flutter·ui·交互·harmonyos
一只大侠的侠9 小时前
Flutter开源鸿蒙跨平台训练营 Day7Flutter+ArkTS双方案实现轮播图+搜索框+导航组件
flutter·开源·harmonyos
那就回到过去9 小时前
VRRP协议
网络·华为·智能路由器·ensp·vrrp协议·网络hcip
相思难忘成疾10 小时前
通向HCIP之路:第四步:边界网关路由协议—BGP(概念、配置、特点、常见问题及其解决方案)
网络·华为·hcip