0

There are tutorials for this on the internet but the code is in Java and I'm new to Kotlin so I am not able to figure out how I can do the same in Kotlin.

The code I tried in Kotlin.

var pattern = longArrayOf(0, 200, 500)

val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
vibrator.vibrate(pattern, 5)

Edit 2: I created a function

@RequiresApi(Build.VERSION_CODES.O)
private fun vibrate(context: Context){
    var pattern = longArrayOf(0, 200, 500)
    val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
    vibrator.vibrate(VibrationEffect.createWaveform(pattern,5))
}

and i called it in the onFinish function of CountDownTimer

@RequiresApi(Build.VERSION_CODES.O)
        override fun onFinish() {
            vibrate(this@MeditateActivity)
        }

i tried running the app on my android device but my device didn't vibrate at all

perpetualdarkness
  • 135
  • 1
  • 4
  • 18
  • This might help you https://stackoverflow.com/questions/5880250/how-to-vibrate-device-n-number-of-times-through-programming-in-android – Ashok Apr 25 '21 at 18:23
  • I did see that link before posting here but that code is in Java and I'm not able to figure out how I can do the same in Kotlin. Can you help me convert that code? thank you – perpetualdarkness Apr 25 '21 at 18:34
  • You've said that you got a compiler error, but now you've said in your question that the device doesn't vibrate? How do you know? – Henry Twist Apr 25 '21 at 19:38
  • I got a compiler error because I didn't include that code in the function and when I did, I didn't have any compiler error anymore. everything looks fine apparently but the device doesn't vibrate – perpetualdarkness Apr 26 '21 at 06:18
  • Well the code you've posted is actually not valid. The `repeat` parameter has to be within the bounds of the `pattern` array. If you try `VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE)` then it should work fine (assuming you have the permission declared properly). Once you have that working you can have another read of the documentation to get an idea for how the other effects work. – Henry Twist Apr 26 '21 at 12:30

0 Answers0