Use it as a top level function in some common class of your project such as Utils.kt
// 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)
}
}
}
And then call it anywhere in your code as following:
vibrateDevice(requireContext())
Using Vibrator::class.java
is more type safe than using String
constants.
We check the vibrator
for nullability using let { }
, because if the vibration is not available for the device, the vibrator
will be null
.
It's ok to supress deprecation in else
clause, because the warning is from newer SDK.
We don't need to ask for permission at runtime for using vibration. But we need to declare it in AndroidManifest.xml
as following:
<uses-permission android:name="android.permission.VIBRATE"/>