To make an Android device vibrate using Kotlin, you can use the Vibrator class from the Android framework. Here's an example of how you can make the device vibrate with different frequencies:
import android.content.Context
import android.os.VibrationEffect
import android.os.Vibrator
fun vibrateDevice(context: Context, milliseconds: Long) {
val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
// Check if the device has a vibrator
if (vibrator.hasVibrator()) {
// Vibrate for the specified milliseconds
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
val vibrationEffect = VibrationEffect.createOneShot(milliseconds, VibrationEffect.DEFAULT_AMPLITUDE)
vibrator.vibrate(vibrationEffect)
} else {
// For devices running older versions than Android Oreo
vibrator.vibrate(milliseconds)
}
}
}
You can call the vibrateDevice()
function with the desired duration in milliseconds to make the device vibrate. For example:
// Vibrate for 500 milliseconds
vibrateDevice(context, 500)
If you want to vibrate with different frequencies, you can use the vibrate()
method with a pattern. Here's an example:
fun vibrateWithPattern(context: Context, pattern: LongArray, repeat: Int) {
val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
// Check if the device has a vibrator
if (vibrator.hasVibrator()) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
val vibrationEffect = VibrationEffect.createWaveform(pattern, repeat)
vibrator.vibrate(vibrationEffect)
} else {
// For devices running older versions than Android Oreo
vibrator.vibrate(pattern, repeat)
}
}
}
In this case, you pass an array of long values representing the durations in milliseconds for which the device should vibrate or remain silent. The repeat
parameter determines whether the pattern should repeat or not (passing -1 will make it not repeat).
Here's an example of how to use the vibrateWithPattern()
function:
// Vibrate with a pattern: vibrate for 200ms, pause for 500ms, vibrate for 300ms
val pattern = longArrayOf(200, 500, 300)
vibrateWithPattern(context, pattern, -1)
This code will make the device vibrate for 200 milliseconds, pause for 500 milliseconds, and then vibrate again for 300 milliseconds. The pattern will not repeat (-1
value for repeat
).
Comments
Post a Comment