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