鴻蒙OS Vibrator開發(fā)指導

2020-09-18 15:48 更新

場景介紹

當設備需要設置不同的振動效果時,可以調用 Vibrator 模塊,例如,設備的按鍵可以設置不同強度和時長的振動,鬧鐘和來電可以設置不同強度和時長的單次或周期性振動。

接口說明

振動器模塊主要提供的功能有:查詢設備上振動器的列表,查詢某個振動器是否支持某種振動效果,觸發(fā)和關閉振動器。VibratorAgent 類開放能力如下,具體請查閱 API 參考文檔。

接口名 描述
getVibratorIdList() 獲取硬件設備上的振動器列表。
isSupport(int) 根據指定的振動器Id查詢硬件設備是否存在該振動器。
isEffectSupport(int, String) 查詢指定的振動器是否支持指定的震動效果。
startOnce(int, String) 對指定的振動器創(chuàng)建指定效果的一次性振動。
startOnce(String) 對指定的振動器創(chuàng)建指定效果的一次性振動。
startOnce(int, int) 對指定的振動器創(chuàng)建指定振動時長的一次性振動。
startOnce(int) 對指定的振動器創(chuàng)建指定振動時長的一次性振動。
start(int, VibrationPattern) 對指定的振動器創(chuàng)建自定義效果的波形或一次性振動。
start(VibrationPattern) 對指定的振動器創(chuàng)建自定義效果的波形或一次性振動。
stop(int, String) 關閉指定的振動器指定模式的振動。
stop(String) 關閉指定的振動器指定模式的振動。

開發(fā)步驟

  1. 控制設備上的振動器,需要在“config.json”里面進行配置請求權限。具體如下:

  1. "reqPermissions": [
  2. {
  3. "name": "ohos.permission.VIBRATE",
  4. "reason": "",
  5. "usedScene": {
  6. "ability": [
  7. ".MainAbility"
  8. ],
  9. "when": "inuse"
  10. }
  11. }
  12. ]

  1. 查詢硬件設備上的振動器列表。

  1. 查詢指定的振動器是否支持指定的震動效果。

  1. 創(chuàng)建不同效果的振動。

  1. 關閉指定的振動器指定模式的振動。

  1. private VibratorAgent vibratorAgent = new VibratorAgent();
  2. private int[] timing = {1000, 1000, 2000, 5000};
  3. private int[] intensity = {50, 100, 200, 255};
  4. @Override
  5. public void onStart(Intent intent) {
  6. super.onStart(intent);
  7. super.setUIContent(ResourceTable.Layout_vibrator_layout);
  8. // ...
  9. // 查詢硬件設備上的振動器列表
  10. List<Integer> vibratorList = vibratorAgent.getVibratorIdList();
  11. if (vibratorList.isEmpty()) {
  12. return;
  13. }
  14. int vibratorId = vibratorList.get(0);
  15. // 查詢指定的振動器是否支持指定的振動效果
  16. boolean isSupport = vibratorAgent.isEffectSupport(vibratorId,
  17. VibrationPattern.VIBRATOR_TPYE_CAMERA_CLICK);
  18. // 創(chuàng)建指定效果的一次性振動
  19. boolean vibrateEffectResult = vibratorAgent.vibrate(vibratorId,
  20. VibrationPattern.VIBRATOR_TPYE_CAMERA_CLICK);
  21. // 創(chuàng)建指定振動時長的一次性振動
  22. int vibratorTiming = 1000;
  23. boolean vibrateResult = vibratorAgent.vibrate(vibratorId, vibratorTiming);
  24. // 創(chuàng)建自定義效果的周期性波形振動
  25. int count = 5;
  26. VibrationPattern vibrationPeriodEffect = VibrationPattern.createPeriod(timing, intensity, count);
  27. boolean vibratePeriodResult = vibratorAgent.vibrate(vibratorId, vibrationPeriodEffect);
  28. // 創(chuàng)建自定義效果的一次性振動
  29. VibrationPattern vibrationOnceEffect = VibrationPattern.createSingle(3000, 50);
  30. boolean vibrateSingleResult = vibratorAgent.vibrate(vibratorId, vibrationOnceEffect);
  31. // 關閉指定的振動器自定義模式的振動
  32. boolean stopResult = vibratorAgent.stop(vibratorId,
  33. VibratorAgent.VIBRATOR_STOP_MODE_CUSTOMIZED);
  34. }
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號