OpenHarmony/HarmonyOS鸿蒙Next震动模块的使用
OpenHarmony/HarmonyOS鸿蒙Next震动模块的使用
震动模块的使用
作者:坚果,公众号:“大前端之旅”,哔哩哔哩,OpenHarmony布道师,OpenHarmony校源行开源大使,电子发烧友鸿蒙MVP,51CTO博客专家博主,阿里云博客专家。
导入模块
使用的时候,需要先导入对应的模块
import vibrator from '@ohos.vibrator';
添加权限
FA
"reqPermissions": [
{
"name": "ohos.permission.VIBRATE"
}
]
Stage
"requestPermissions": [
{
"name": "ohos.permission.VIBRATE"
}
]
vibrator.vibrate
vibrate(duration: number): Promise
按照指定持续时间触发马达振动。需要添加权限
参数:
参数名 | 类型 | 必填 | 说明 |
---|---|---|---|
duration | number | 是 | 指示马达振动的持续时间。 |
返回值:
类型 | 说明 |
---|---|
Promise | 指示触发振动是否成功。 |
示例:
import vibrator from '@ohos.vibrator';
@Entry
@Component
struct VibPage {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold).onClick(()=>
vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(()=>{
console.log("Promise returned to indicate a successful vibration.");
}, (error)=>{
console.log("error.code"+error.code+"error.message"+error.message);
});
)
}
.width('100%')
}
.height('100%')
}
}
需要注意的是
接口声明文件编写错误,需要手动修改下SDK目录下接口声明文件,文件路径Sdk\openharmony\8\ets\api@ohos.vibrator.d.ts
修改vibrate方法顺序为
function vibrate(duration: number): Promise;
function vibrate(duration: number, callback?: AsyncCallback): void;
更多关于OpenHarmony/HarmonyOS鸿蒙Next震动模块的使用的实战教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
在OpenHarmony/HarmonyOS鸿蒙Next中,震动模块的使用主要通过vibrator
API实现。首先,在config.json
中声明ohos.permission.VIBRATE
权限。然后,使用vibrator.startVibration
方法启动震动,传入震动模式和持续时间。例如:
import vibrator from '@ohos.vibrator';
vibrator.startVibration({
type: 'time', // 震动模式
duration: 1000 // 持续时间,单位毫秒
}, (err) => {
if (err) {
console.error('Vibration failed:', err);
} else {
console.log('Vibration started');
}
});
停止震动可使用vibrator.stopVibration
方法。