Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

[Guide] Haptic Feedback on Android with no Plugin

Discussion in 'Android' started by Zocker1996, Jan 28, 2016.

  1. Zocker1996

    Zocker1996

    Joined:
    Jan 12, 2015
    Posts:
    20
    Hi!

    So it took me 4 hours to figure out Haptic Feedback on Android without a plugin (which would be easly made, but I just didn't want to).
    Keep in mind that this is just Haptic Feedback and not a fully functional vibrator!
    I would be happy if someone could post other, non-plugin Haptic Feedback solutions.
    I post this here since I think this is not Asset worthy and to see other, maybe better solutions.

    The advantages of my method are:
    -No need for vibration permission and thiswhile no custom AndroidManifest needed
    -If the user disables Haptic Feedback on his device in general, there is no Haptic Feedback here, too

    You would just call AndroidManager.HapticFeedback();


    Code (CSharp):
    1. using UnityEngine;
    2. public class AndroidManager : MonoBehaviour
    3. {
    4. private class HapticFeedbackManager
    5.     {
    6.     #if UNITY_ANDROID && !UNITY_EDITOR
    7.         private int HapticFeedbackConstantsKey;
    8.         private AndroidJavaObject UnityPlayer;
    9.     #endif
    10.  
    11.         public HapticFeedbackManager(){
    12.             #if UNITY_ANDROID && !UNITY_EDITOR
    13.             HapticFeedbackConstantsKey=new AndroidJavaClass("android.view.HapticFeedbackConstants").GetStatic<int>("VIRTUAL_KEY");
    14.             UnityPlayer=new AndroidJavaClass ("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity").Get<AndroidJavaObject>("mUnityPlayer");
    15.             //Alternative way to get the UnityPlayer:
    16.             //int content=new AndroidJavaClass("android.R$id").GetStatic<int>("content");
    17.             //new AndroidJavaClass ("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity").Call<AndroidJavaObject>("findViewById",content).Call<AndroidJavaObject>("getChildAt",0);
    18.             #endif
    19.         }
    20.  
    21.         public bool Execute(){
    22.             #if UNITY_ANDROID && !UNITY_EDITOR
    23.             return UnityPlayer.Call<bool> ("performHapticFeedback",HapticFeedbackConstantsKey);
    24.             #endif
    25.             return false;
    26.         }
    27.     }
    28.  
    29.     //Cache the Manager for performance
    30.     private static HapticFeedbackManager mHapticFeedbackManager;
    31.  
    32.     public static bool HapticFeedback(){
    33.         if (mHapticFeedbackManager == null) {
    34.             mHapticFeedbackManager = new HapticFeedbackManager ();
    35.         }
    36.         return mHapticFeedbackManager.Execute ();
    37.     }
    38. }
     
    Last edited: Jan 28, 2016
    creative_vlad and Anvoker like this.