65

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);
    }
}
Yogesh Umesh Vaity
  • 41,009
  • 21
  • 145
  • 105
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154

9 Answers9

37

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)
    }
}
aolphn
  • 2,950
  • 2
  • 21
  • 30
27

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

Kapil G
  • 4,081
  • 2
  • 20
  • 32
15

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 ...

Bob
  • 13,447
  • 7
  • 35
  • 45
12

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.

Yogesh Umesh Vaity
  • 41,009
  • 21
  • 145
  • 105
5

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.

hardysim
  • 2,756
  • 2
  • 25
  • 52
  • Note that pattern will work in two different ways here. `createWaveform` accepts timings and amplitudes, and vibrate accepts paired off/on timings. – Ivan Shafran Jan 29 '21 at 06:15
2

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

All you would need is Rumble.once(150);

It handles the API versions for you.

jojois74
  • 795
  • 5
  • 10
2

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 ✌ :))

Serg Burlaka
  • 2,351
  • 24
  • 35
1

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){}
Newred
  • 699
  • 8
  • 8
  • 1
    It's already in ms . No need to convert anything: https://developer.android.com/reference/android/os/Vibrator.html#vibrate(long) . Just one line of code is needed. – android developer Jun 13 '19 at 07:36
1
 @Suppress("DEPRECATION")
    fun setVibrationSettings(context: Context, isVibrationOn: Boolean) {
        val vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            val vibrationEffect =
                VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE)
            (context.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager).run {
                if (isVibrationOn) {
                    this.defaultVibrator.vibrate(vibrationEffect)
                } else {
                    this.defaultVibrator.cancel()
                }
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val vibrationEffect =
                VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE)
            (context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator).run {
                if (isVibrationOn) {
                    this.vibrate(vibrationEffect)
                } else {
                    this.cancel()
                }
            }
        } else {
            (context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator).run {
                if (isVibrationOn) {
                    this.vibrate(1000)
                } else {
                    this.cancel()
                }
            }
        }
    }

Code with check SDK for 31 and 26 SDK

ADD permission

 <uses-permission android:name="android.permission.VIBRATE"/>
Vlad Bulan
  • 157
  • 13