Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android vibrate is deprecated. How to use VibrationEffect in Android>= API 26?

I am using Android's VIBRATOR_SERVICE to give a haptic feedback for a button touch.

 ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(300); 

Android Studio give me warning that method vibrate(interval) is deprecated I should use VibrationEffect for API>23.

So I usedVibrationEffect's method createOneShot which takes 2 params: interval, and amplitude. enter image description here

I tried searching for it but got no clue about what to pass as amplitude, anybody got any idea about how to use it?

Update Added code

// Vibrate for 150 milliseconds private void shakeItBaby() {     if (Build.VERSION.SDK_INT >= 26) {         ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150,10));     } else {         ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(150);     } } 
like image 734
Hitesh Sahu Avatar asked Aug 10 '17 05:08

Hitesh Sahu


2 Answers

with kotlin

private fun vibrate(){     val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {          vibrator.vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE))     } else {          vibrator.vibrate(200)     } } 
like image 134
aolphn Avatar answered Sep 23 '22 13:09

aolphn


Amplitude is an int value. Its The strength of the vibration. This must be a value between 1 and 255, or DEFAULT_AMPLITUDE which is -1.

You can use it as VibrationEffect.DEFAULT_AMPLITUDE

More details here

like image 42
Kapil G Avatar answered Sep 23 '22 13:09

Kapil G