【HarmonyOS】应用振动效果实现

ops/2024/9/22 15:48:06/

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

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

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

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

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

  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/ops/47222.html

相关文章

leetcode74搜索二维矩阵

题目 给你一个满足下述两条属性的 m x n 整数矩阵: 每行中的整数从左到右按非严格递增顺序排列。每行的第一个整数大于前一行的最后一个整数。 给你一个整数 target ,如果 target 在矩阵中,返回 true ;否则,返回 fa…

国外创意二维码营销案例:巴西宠物食品品牌户外活动“救救宠物爪子吧”

2024年5月份,巴西宠物食品品牌Purina Brasil 与广告公司Publicis Brasil合作,推出了一次特别的户外营销活动——Salve as Patinhas(Save the Paws)(救救宠物爪子吧),非常有意思! 随着全球气候变暖&#xf…

ARM32开发——GPIO输入

🎬 秋野酱:《个人主页》 🔥 个人专栏:《Java专栏》《Python专栏》 ⛺️心若有所向往,何惧道阻且长 文章目录 按键点灯一按键点灯二完整代码按钮输入的接线方式消除抖动硬件消抖 按键点灯一 ● 按下按键,LED1亮 ● 抬起按键&#…

MaaS玩家:希望AI大模型价格战再狠一点

明知产能严重过剩的新能源企业却还在重金扩产,多半因为他们花的不是自己的钱;明知极度烧钱的AI大模型却开始打价格战,多半因为他们并不靠这东西挣钱。 所有投资人必备的一项技能,就是中观行业景气度及商业模式对比。很明显&#…

Django 解决 CSRF 问题

在 Django 出现 CSRF 问题 要解决这个问题&#xff0c;就得在 html 里这么修改 <!DOCTYPE html> <html><head></head><body><form action"/login/" method"post">{% csrf_token %}</form></body> </…

【异常分析:四分位距与3σ原则】

文章目录 前言四分位距&#xff08;IQR&#xff09;3σ原则使用步骤计算四分位距应用3σ原则 代码 前言 异常分析的目标是识别数据中的异常值&#xff0c;这些异常值可能是由于错误的记录、设备故障或者其他未知原因导致的。四分位距&#xff08;interquartile range, IQR&…

WebStorm 2024.1.1 Mac激活码 前端开发工具集成开发环境(IDE)

WebStorm 2024 Mac激活码 搜索Mac软件之家下载WebStorm 2024 Mac激活版 WebStorm 2024 功能介绍 WebStorm 2024是由JetBrains公司开发的一款专为前端开发设计的集成开发环境&#xff08;IDE&#xff09;。它提供了一整套功能&#xff0c;旨在提高Web开发者的工作效率和代码质…

数字塔问题

#include<iostream> using namespace std; //从下向上得到最优值 void dtower(int a[][100],int s[][100],int n) {for(int in; i>1; i--){for(int j1; j<i; j){if(in)s[i][j]a[i][j];else{int ts[i1][j];if(t<s[i1][j1])ts[i1][j1];s[i][j]a[i][j]t;}}} } void…