Creating a vibrator for Android in Kotlin

Viewed 40

I'm trying to add vibration effects to my Android game. I found some code that seems to work, but it's deprecated. What's the current way to create and deploy a vibrator?

var vibrator:Vibrator = getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE) as Vibrator

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
               vibrator.vibrate(createPredefined(EFFECT_CLICK))
            }else{
                vibrator.vibrate(50)
            }

The parts that are showing up as deprecated are "VIBRATOR-SERVICE" and vibrate.vibrate(50).

1 Answers

Step 1 : Add permission to the AndroidMenifest.xml

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

Step 2 : You can use this function for vibration.

fun vibrate(ctx: Context?) {
        if (ctx != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                val vibratorManager =
                    ctx.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
                val vibrator = vibratorManager.defaultVibrator
                vibrator.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK))
            } else {
                val v = ctx.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    v.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK))
                } else {
                    v.vibrate(200L)
                }
            }
        }
    }
Related