How to vibrate Android device on button click using vibrator effects using Kotlin?

Davinder Goel picture Davinder Goel · Dec 19, 2017 · Viewed 12k times · Source

How to vibrate an Android device coding with Kotlin when pressing any buttons? I have used this code below, but there aren't any effects or vibrations performed.

//click listener
    imgNextBtn.setOnClickListener {
        val vibe:Vibrator = activity?.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        vibe.vibrate(500)
        Utilities.alertDialog(this,
                activity!!,
                mContent!!
    }
}

Or

 //click listener
    imgNextBtn.setOnClickListener {
        val vibe:Vibrator = activity?.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        var effect:VibrationEffect = VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE);

    vibe.vibrate(effect)
        
        Utilities.alertDialog(this,
                activity!!,
                mContent!!
    }
}

Android Manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.china.openkey">

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

Answer

jo jo picture jo jo · Sep 11, 2018

You can create a fun and use from it (Kotlin):

fun Fragment.vibratePhone() {
    val vibrator = context?.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
    if (Build.VERSION.SDK_INT >= 26) {
        vibrator.vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE))
    } else {
        vibrator.vibrate(200)
    }
}

And in your fragment:

vibratePhone()

Finally in you manifest:

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