PhoneVibrateTool.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /****************************************************************************
  2. * Copyright 2019 Nreal Techonology Limited. All rights reserved.
  3. *
  4. * This file is part of NRSDK.
  5. *
  6. * https://www.nreal.ai/
  7. *
  8. *****************************************************************************/
  9. namespace NRKernal
  10. {
  11. using System;
  12. using UnityEngine;
  13. /// <summary> A phone vibrate tool. </summary>
  14. internal class PhoneVibrateTool
  15. {
  16. #if UNITY_ANDROID && !UNITY_EDITOR
  17. public AndroidJavaClass unityPlayer;
  18. public AndroidJavaObject currentActivity;
  19. public AndroidJavaObject vibrator;
  20. private static PhoneVibrateTool _instance;
  21. public PhoneVibrateTool()
  22. {
  23. unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
  24. currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
  25. vibrator = currentActivity.Call<AndroidJavaObject>("getSystemService", "vibrator");
  26. //to make unity auto add vibrate user permission
  27. if (Application.isEditor)
  28. Handheld.Vibrate();
  29. }
  30. private void DoVibrate()
  31. {
  32. vibrator.Call("vibrate");
  33. }
  34. private void DoVibrate(long milliseconds)
  35. {
  36. vibrator.Call("vibrate", milliseconds);
  37. }
  38. private void DoVibrate(long[] pattern, int repeat)
  39. {
  40. vibrator.Call("vibrate", pattern, repeat);
  41. }
  42. private void CancelVibrate()
  43. {
  44. vibrator.Call("cancel");
  45. }
  46. private bool HasVibrator()
  47. {
  48. return vibrator.Call<bool>("hasVibrator");
  49. }
  50. #endif
  51. /// <summary> Trigger vibrate. </summary>
  52. /// <param name="durationSeconds"> (Optional) The duration in seconds.</param>
  53. public static void TriggerVibrate(float durationSeconds = 0.1f)
  54. {
  55. #if UNITY_ANDROID && !UNITY_EDITOR
  56. if (_instance == null)
  57. _instance = new PhoneVibrateTool();
  58. if(_instance != null && _instance.HasVibrator())
  59. _instance.DoVibrate((long)(durationSeconds * 1000f));
  60. #endif
  61. }
  62. }
  63. }