Skip to content

Instantly share code, notes, and snippets.

@aVolpe
Created October 16, 2014 02:45
Star You must be signed in to star a gist
Save aVolpe/707c8cf46b1bb8dfb363 to your computer and use it in GitHub Desktop.
Vibration for Unity3d with Android native Call, with fallback to Handlheld.Vibrate()
using UnityEngine;
using System.Collections;
public static class Vibration
{
#if UNITY_ANDROID && !UNITY_EDITOR
public static AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
public static AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
public static AndroidJavaObject vibrator = currentActivity.Call<AndroidJavaObject>("getSystemService", "vibrator");
#else
public static AndroidJavaClass unityPlayer;
public static AndroidJavaObject currentActivity;
public static AndroidJavaObject vibrator;
#endif
public static void Vibrate()
{
if (isAndroid())
vibrator.Call("vibrate");
else
Handheld.Vibrate();
}
public static void Vibrate(long milliseconds)
{
if (isAndroid())
vibrator.Call("vibrate", milliseconds);
else
Handheld.Vibrate();
}
public static void Vibrate(long[] pattern, int repeat)
{
if (isAndroid())
vibrator.Call("vibrate", pattern, repeat);
else
Handheld.Vibrate();
}
public static bool HasVibrator()
{
return isAndroid();
}
public static void Cancel()
{
if (isAndroid())
vibrator.Call("cancel");
}
private static bool isAndroid()
{
#if UNITY_ANDROID && !UNITY_EDITOR
return true;
#else
return false;
#endif
}
}
@breban1
Copy link

breban1 commented Feb 20, 2017

Thanks so much!

@CasulScrub
Copy link

Vibration.Vibrate ( ͡° ͜ʖ ͡°));
Thank you for this, works great!

@Xorboo
Copy link

Xorboo commented Oct 22, 2017

Works perfect, but i see that the calls are deprecated from API level 26. Any idea how to switch this for using VibrationEffect object?
I tried doing something like this, but its crashing on the first line:

var jo = new AndroidJavaClass("android.os.VibrationEffect");  // "core.java.android.os.VibrationEffect" is crashing too
var effect = jo.CallStatic<object>("createOneShot", milliseconds, 255);
vibrator.Call("vibrate", effect);

@AdriaandeJongh
Copy link

would also like to know the above!

@AdriaandeJongh
Copy link

(I would also like to note that this code won't run without the Vibrate permission, which Unity adds automatically when you have Handheld.Vibrate(); somewhere in your code, even when you don't use it.)

@AdriaandeJongh
Copy link

(I would ALSO like to note that simply entering plain numbers in the 'duration' field will cast them to INT while the vibration functions require them to be LONG values!)

@greenKour
Copy link

THANK YOUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU!!!!!!!!!!!!!!!!!!!

@playfulbacon
Copy link

playfulbacon commented Nov 28, 2017

@Xorboo @AdriaandeJongh

I got VibrationEffect working like this:

AndroidJavaObject vibrationEffect = vibrationEffectClass.CallStatic<AndroidJavaObject>(function, args);
vibrator.Call("vibrate", vibrationEffect);

I made my own gist that works with API level 26 here.

@Splashcom
Copy link

Splashcom commented Jan 16, 2018

Some license? Or free use?
App crashes for Unity 2017.1.1f1. Someone can confirm?
Handheld.Vibrate(); still working.

@wfowler1
Copy link

The implementation of HasVibrator is wrong. The best way to do that would probably be this:
return vibrator.Call<bool>("hasVibrator");

@prajwalbhat7
Copy link

Thanks a Lot! (y)

@Wolfie34
Copy link

Thanks it's working

@dvdmrn
Copy link

dvdmrn commented Jun 18, 2019

This doesn't seem to be working for me. I get the following error when running:
Vibration' is missing the class attribute 'ExtensionOfNativeClass'!

I changed the class name from Vibration-->Vibration1 and that got rid of the error. But when calling Vibration1.Vibrate() the console prints iPhoneUtils.Vibrate() implying it's using Handheld.Vibrate() which isn't working for Android.

(I'm using Unity 2018.3.0 and testing w/ UnityRemote 5)

Edit: found out that debugging in UnityRemote does not support vibrations... that's probably the crux of it. When building, Handheld.Vibrate() worked

@AlexanderCrane
Copy link

This doesn't seem to be working for me either. My application crashes on start, but no notable logs reveal the cause of the crash in logcat.

I'm using Unity 2019.2.9f1, with my minumum API level set to 25, and Mono and .NET 2.0.

Has anyone figured out why this causes it to crash?

@mukolah
Copy link

mukolah commented Nov 14, 2019

Thank you! Works great on Unity 2019.2.8f1, Android 9.
Vibration.Vibrate(100) works like a charm.

@ruzrobert
Copy link

Hi all! I've made a drastically improved version.

Script automatically detects Api Level. Checks if Amplitude control (API >= 26) is available. Also supports Predefined Effects (API >= 29).
If API is < 26, legacy functions are used (old api).

Code is available here: github gist link

@escaper01
Copy link

it worked from the first try
<3<3<3<3<3<3<3<3<3
thank you @aVolpe

@iqfareez
Copy link

iqfareez commented Apr 24, 2020

Hi. Here made an app based on the script created by ruzrobert above. For dev out there who want to test and tweak how vibration should feel on devices. Available only Android. Can download via Play Store: https://play.google.com/store/apps/details?id=com.maplerr.TestVibration .

@zlaughingdragon
Copy link

Appreciate the code!

@Andrei114
Copy link

Vibration' is missing the class attribute 'ExtensionOfNativeClass'!

I deleted the "static" from "public static class" and added after "class" ": MonoBehaviour"

from
public static class Vibration
to
public class Vibration : MonoBehaviour

@debianop
Copy link

debianop commented Dec 5, 2020

Thanks for good class.

@zxt5105515
Copy link

in unity2019.4.10f1,

get error c# exception:UnityEngine.AndroidJavaException: java.lang.NoSuchMethodError: no non-static method with name='vibrate' signature='()V' in class Landroid.os.SystemVibrator;

change vibrator.Call("vibrate"); to vibrator.Call("vibrate" ,100); may fix it

@agustinaA-Lopez
Copy link

didn't work with Vibration.vibrate(x) but it does with Vibration1.vibrate(x). didn't change the script Vibration.cs. The mystery of informatics ...
Other than that works perfect! thank you!!!

This doesn't seem to be working for me. I get the following error when running:
Vibration' is missing the class attribute 'ExtensionOfNativeClass'!

I changed the class name from Vibration-->Vibration1 and that got rid of the error. But when calling Vibration1.Vibrate() the console prints iPhoneUtils.Vibrate() implying it's using Handheld.Vibrate() which isn't working for Android.

(I'm using Unity 2018.3.0 and testing w/ UnityRemote 5)

Edit: found out that debugging in UnityRemote does not support vibrations... that's probably the crux of it. When building, Handheld.Vibrate() worked

@diliupg
Copy link

diliupg commented Feb 24, 2021

Great code. Worrks well in Unity 2020.1.17f1. Thanks! Be blessed!

@alllt1r
Copy link

alllt1r commented Apr 1, 2021

Thank you for this, everything works great!
Unity 2020.3.2f1 Personal
Vibration.Vibrate(100);

@SamKyada
Copy link

SamKyada commented Sep 14, 2021

'Vibration' is missing the class attribute 'ExtensionOfNativeClass'!
how to Solve this error.......
Unity 2020.3.17f1

@khOsman1917
Copy link

Thank you😊

@maryphun
Copy link

Doesn't expect this still work in 2022.
You're a hero

@diliupg
Copy link

diliupg commented Jan 21, 2022

@SamKyada , read the reply by @agustinaA-Lopez

@pflosch
Copy link

pflosch commented Dec 19, 2023

meanwhile 2023, Android14, copy, paste, works like a charm.
Thanks @aVolpe , you're the man...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment