Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using UnityEngine;
- using Zenject;
- namespace _Project.CodeBase.Services.Vibration
- {
- public class Vibrator : IInitializable, IDisposable
- {
- public bool AndroidSupported { get; private set; }
- public bool Enabled
- {
- get => _enabled;
- set
- {
- if (!AndroidSupported)
- return;
- _enabled = value;
- }
- }
- private const string VibrationSignal = "vibrate";
- private const string CancelSignal = "cancel";
- private AndroidJavaClass _unityPlayer;
- private AndroidJavaObject _currentActivity;
- private AndroidJavaObject _systemVibrator;
- private bool _enabled;
- public void Initialize()
- {
- #if UNITY_ANDROID && !UNITY_EDITOR
- _unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
- _currentActivity = _unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
- _systemVibrator = _currentActivity.Call<AndroidJavaObject>("getSystemService", "vibrator");
- AndroidSupported = _systemVibrator.Call<bool>("hasVibrator");
- #endif
- }
- public void Dispose() =>
- Cancel();
- public void Vibrate()
- {
- Debug.Log($"Enabled: {Enabled} | Supported: {AndroidSupported}");
- if (!Enabled)
- return;
- if (AndroidSupported)
- {
- _systemVibrator.Call(VibrationSignal);
- Debug.Log("Vibrate!");
- return;
- }
- Handheld.Vibrate();
- }
- public void Vibrate(long milliseconds)
- {
- if (!Enabled)
- return;
- if (AndroidSupported)
- _systemVibrator.Call(VibrationSignal, milliseconds);
- else
- Handheld.Vibrate();
- }
- public void Vibrate(long[] pattern, int repeat)
- {
- if (!Enabled)
- return;
- if (AndroidSupported)
- _systemVibrator.Call(VibrationSignal, pattern, repeat);
- else
- Handheld.Vibrate();
- }
- public void Cancel()
- {
- if (AndroidSupported)
- _systemVibrator.Call(CancelSignal);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement