【HarmonyOS】应用振动效果实现

devtools/2024/9/25 17:16:45/

一、问题背景:
应用在强提醒场景下,一般会有马达振动的效果,提示用户注意力的关注。

比如消息提醒,扫码提示,删除键确认提示等。

针对高定制化或者固定的振动方式,我们需要有不同的方案实现,马达振动效果。

二、解决方案:
鸿蒙针对振动效果的实现,有多种方案,目前分为振动和音振协同两种方式。

单纯的只是振动,又分为三种方式:

  1. 系统定制的振动方式,例如闹钟
  2. 非系统定制,自定义振动配置json文件的方式
  3. 线性马达振动,只需要设置时间和强度(最简单的调用方式)

音振协同一般用于,音效播放和振动同时的场景,例如扫码

1.首先需要配置振动权限,该权限是系统权限,只需要配置后,默认就会被授权。
ohos.permission.VIBRATE

2.之后根据需要实现不同的马达振动效果,方案调用详情参见下方代码示例的注释。

三、DEMO示例:

import vibrator from '@ohos.vibrator';
import { BusinessError } from '@ohos.base';
import { resourceManager } from '@kit.LocalizationKit';/*** 振动管理类* 需要权限: ohos.permission.VIBRATE*/
export class HapticMgr {private TAG: string = 'HapticMgr';private static mHapticMgr: HapticMgr | undefined = undefined;public static Ins(): HapticMgr{if(!HapticMgr.mHapticMgr){HapticMgr.mHapticMgr = new HapticMgr();}return HapticMgr.mHapticMgr;}/*** 按照指定持续时间触发马达振动*/public timeVibration(){try {// 触发马达振动vibrator.startVibration({type: 'time',duration: 1000,}, {id: 0,usage: 'alarm'}, (error: BusinessError) => {if (error) {console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`);return;}console.info('Succeed in starting vibration');});} catch (err) {let e: BusinessError = err as BusinessError;console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`);}}/*** 按照预置振动效果触发马达振动,可先查询振动效果是否被支持,再调用振动接口*/public typeVibration(){try {// 查询是否支持'haptic.clock.timer'vibrator.isSupportEffect('haptic.clock.timer', (err: BusinessError, state: boolean) => {if (err) {console.error(`Failed to query effect. Code: ${err.code}, message: ${err.message}`);return;}console.info('Succeed in querying effect');if (state) {try {// 触发马达振动vibrator.startVibration({type: 'preset',effectId: 'haptic.clock.timer',count: 1,}, {usage: 'unknown'}, (error: BusinessError) => {if (error) {console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`);} else {console.info('Succeed in starting vibration');}});} catch (error) {let e: BusinessError = error as BusinessError;console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`);}}})} catch (error) {let e: BusinessError = error as BusinessError;console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`);}}public fileVibration(){const fileName: string = 'vibration.json';// 获取文件资源描述符let rawFd: resourceManager.RawFileDescriptor = getContext().resourceManager.getRawFdSync(fileName);// 触发马达振动try {vibrator.startVibration({type: "file",hapticFd: { fd: rawFd.fd, offset: rawFd.offset, length: rawFd.length }}, {id: 0,usage: 'alarm'}, (error: BusinessError) => {if (error) {console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`);return;}console.info('Succeed in starting vibration');});} catch (err) {let e: BusinessError = err as BusinessError;console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`);}// 关闭文件资源描述符getContext().resourceManager.closeRawFdSync(fileName);}/*** 按照指定模式停止对应的马达振动,自定义振动不支持此类停止方式*/public stopVibrationByType(){//  停止固定时长振动try {// 按照VIBRATOR_STOP_MODE_TIME模式停止振动vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, (error: BusinessError) => {if (error) {console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`);return;}console.info('Succeed in stopping vibration');})} catch (err) {let e: BusinessError = err as BusinessError;console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`);}// 停止预置振动try {// 按照VIBRATOR_STOP_MODE_PRESET模式停止振动vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, (error: BusinessError) => {if (error) {console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`);return;}console.info('Succeed in stopping vibration');})} catch (err) {let e: BusinessError = err as BusinessError;console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`);}}/*** 停止所有模式的马达振动,包括自定义振动:*/public stopVibration(){try {// 停止所有模式的马达振动vibrator.stopVibration((error: BusinessError) => {if (error) {console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`);return;}console.info('Succeed in stopping vibration');})} catch (error) {let e: BusinessError = error as BusinessError;console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`);}}}

振动配置文件:
在这里插入图片描述

{"MetaData": {"Create": "2023-01-09","Description": "a haptic case","Version": 1.0,"ChannelNumber": 1},"Channels": [{"Parameters": {"Index": 0},"Pattern": [{"Event": {"Type": "transient","StartTime": 0,"Parameters": {"Frequency": 31,"Intensity": 100}}},{"Event": {"Type": "continuous","StartTime": 40,"Duration": 54,"Parameters": {"Frequency": 30,"Intensity": 38,"Curve": [{"Time": 0,"Frequency": 0,"Intensity": 0},{"Time": 1,"Frequency": 15,"Intensity": 0.5},{"Time": 40,"Frequency": -8,"Intensity": 1.0},{"Time": 54,"Frequency": 0,"Intensity": 0}]}}}]}]
}

http://www.ppmy.cn/devtools/46422.html

相关文章

OBD诊断协议

上周领导需要做个OBD相关的功能,我对OBD没有啥概念,于是周末就了解下这到底是个啥东西。了解过后发现很简单,其实就是个UDS协议的简化版,OBD是英文On-Board Diagnostics的缩写,中文翻译为“车载自动诊断系统”&#xf…

锐捷校园网自助服务-字符过滤存在缺陷

锐捷校园网自助服务-字符过滤存在缺陷 漏洞介绍 令人感到十分遗憾的是,锐捷网络安全应急响应中心对漏洞上报似乎缺少了一些奖励,令人对官方上报漏洞失去了些许兴趣​。 该缺陷仅仅打破了安全检查防护,并没有造成实质性危害,至于…

spark学习记录-spark基础概念

背景需求 公司有项目需要将大容量数据进行迁移,经过讨论,采用spark框架进行同步、转换、解析、入库。故此,这里学习spark的一些基本的概念知识。 Apache Spark 是一个开源的大数据处理框架,可以用于高效地处理和分析大规模的数据…

[Redis]List类型

列表类型来存储多个有序的字符串,a、b、c、d、e 五个元素从左到右组成了一个有序的列表,列表中的每个字符串称为元素,一个列表最多可以存储个元素。在 Redis 中,可以对列表两端插入(push)和弹出&#xff08…

ubuntu 20.04安装桌面并远程连接

参考: https://www.zmy6.com/archives/234 https://blog.csdn.net/weixin_42068573/article/details/131227544 https://blog.csdn.net/LoongEmbedded/article/details/132434219 sudo apt install ubuntu-desktopsudo apt install xrdpsudo systemctl status xrdpp…

【Git】

一、git介绍 git - 分布式版本控制工具Version control systems(VCSs) VS 集中式版本控制工具 Git 是一个免费的、开源的分布式版本控制系统,可以快速高效地处理从小型到大型的各种项目。 Git 易于学习,占地面积小,性能极快。它具有廉价的…

华为SSH实验

华为SSH实验 实验拓扑: 实验要求:从SSH客户端AR1采用stelnet方式登录到SSH 服务器端。 实验步骤: 1.完成基本配置(略) sys Enter system view, return user view with CtrlZ. [AR1]sys CLIENT [CLIENT]INT g0/0/0 [C…

Flutter 中的 ParentDataWidget 小部件:全面指南

Flutter 中的 ParentDataWidget 小部件:全面指南 Flutter 是一个由 Google 开发的跨平台 UI 框架,它提供了丰富的组件来帮助开发者构建高性能、美观的应用。在 Flutter 的布局体系中,ParentDataWidget 是一个抽象类,用于定义如何…