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

JavaAndroidKotlinAndroid 8.0-OreoAndroid Vibration

Java Problem Overview


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);
    }
}

Java Solutions


Solution 1 - Java

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)
    }
}

Solution 2 - Java

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

Solution 3 - Java

You can use this for haptic feedback (vibration):

view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);

There are other constants available in HapticFeedbackConstants like VIRTUAL_KEY, KEYBOARD_TAP ...

Solution 4 - Java

Updated for Kotlin

// Vibrates the device for 100 milliseconds.
fun vibrateDevice(context: Context) {
    val vibrator = getSystemService(context, Vibrator::class.java)
    vibrator?.let {
        if (Build.VERSION.SDK_INT >= 26) {
            it.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE))
        } else {
            @Suppress("DEPRECATION")
            it.vibrate(100)
        }
    }
}

Call the function as following:

vibrateDevice(requireContext())

Make sure you add permission to AndroidManifest.xml as following:

<uses-permission android:name="android.permission.VIBRATE"/>

Note that you don't need to ask for permission at runtime for using vibration.

You need to suppress deprecation in else clause, because the warning is from newer SDK.

Solution 5 - Java

I just stumbled across this and found out that VibrationEffect.createWaveform() basically uses the same long[]-pattern as the old vibrate().

Because of this, you can reuse your existing pattern like so (this is a Kotlin extension-function):

fun Context.vibrate(pattern: LongArray) {
    val vibrator =
        applicationContext.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator? ?: return

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        vibrator.vibrate(
            VibrationEffect.createWaveform(pattern, VibrationEffect.DEFAULT_AMPLITUDE)
        )

    } else {
        @Suppress("DEPRECATION")
        vibrator.vibrate(pattern, -1)
    }
}

And instead of VibrationEffect.createOneShot() you can use a pattern as well (e.g. longArrayOf(0, 150)) so no need to use different functions.

Solution 6 - Java

working for me kotlin ext fun

for the haptic effect, vibro has 5 milliseconds!! (SHORT_HAPTIC_FEEDBACK_DURATION)

fun Context.performHapticFeedback() {
    val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val vibrationEffect = VibrationEffect.createOneShot(HAPTIC_FEEDBACK_DURATION, VibrationEffect.DEFAULT_AMPLITUDE)
        vibrator.vibrate(vibrationEffect)
    } else {
        vibrator.vibrate(TimeUnit.MILLISECONDS.toMillis(SHORT_HAPTIC_FEEDBACK_DURATION))
    }
}

private const val SHORT_HAPTIC_FEEDBACK_DURATION = 5L

usage

addOnItemTouchListener(ItemTouchListener { position, event ->
                if (event.action == MotionEvent.ACTION_DOWN) {
                    context.performHapticFeedback()  
                }  
            })

permission

 <uses-permission android:name="android.permission.VIBRATE"/>

good luck ✌ :))

Solution 7 - Java

This library may help you out: https://github.com/josephrubin/Rumble-4-Android

All you would need is

It handles the API versions for you.

Solution 8 - Java

enter image description hereOpen Manage NuGet Packages

Search and Install Xamarin.Essentials

try {
 var duration = TimeSpan.FromMilliseconds(300);
 Vibration.Vibrate(duration);
} 
 catch (FeatureNotSupportedException ex){} 
 catch (Exception ex){}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHitesh SahuView Question on Stackoverflow
Solution 1 - JavaaolphnView Answer on Stackoverflow
Solution 2 - JavaKapil GView Answer on Stackoverflow
Solution 3 - JavaBobView Answer on Stackoverflow
Solution 4 - JavaYogesh Umesh VaityView Answer on Stackoverflow
Solution 5 - JavahardysimView Answer on Stackoverflow
Solution 6 - JavaSerg BurlakaView Answer on Stackoverflow
Solution 7 - Javajojois74View Answer on Stackoverflow
Solution 8 - JavaNewredView Answer on Stackoverflow