vibrate.ets 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { vibrator } from '@kit.SensorServiceKit';
  2. import { BusinessError } from '@kit.BasicServicesKit';
  3. /**
  4. * 原生振动控制类
  5. * 用于控制设备振动,提供触觉反馈
  6. */
  7. export class VibrateNative {
  8. /**
  9. * 使设备振动指定时长
  10. * @param duration 振动持续时间(毫秒)
  11. */
  12. static vibrate(duration: number): void {
  13. try {
  14. // 调用系统振动API
  15. vibrator.startVibration(
  16. {
  17. type: 'time', // 振动类型为时间模式
  18. duration: duration // 振动持续时间
  19. },
  20. {
  21. id: 0, // 振动任务ID
  22. usage: 'alarm' // 振动场景类型,用于系统开关管控
  23. },
  24. (error: BusinessError) => {
  25. // 错误处理回调
  26. if (error) {
  27. console.error(
  28. `振动启动失败: 错误码 ${error.code}, 错误信息 ${error.message}`
  29. );
  30. return;
  31. }
  32. }
  33. );
  34. } catch (err) {
  35. // 捕获意外错误
  36. const error: BusinessError = err as BusinessError;
  37. console.error(
  38. `发生意外错误: 错误码 ${error.code}, 错误信息 ${error.message}`
  39. );
  40. }
  41. }
  42. }