20

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" />
Bay
  • 467
  • 7
  • 22
Davinder Goel
  • 763
  • 2
  • 8
  • 22

6 Answers6

40

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" />
jo jo
  • 1,758
  • 3
  • 20
  • 34
13

Answer given by @R2R is perfect. But vibrate() method of Vibrator class is deprecated from API Level 26. So, I am giving you the updated code:

You don't have to change everything. Just update the code for vibration in MainActivity.kt.

MainActivity.kt:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main);

        val btn_click_me = findViewById(R.id.btn_vibrate) as Button
        btn_click_me.setOnClickListener {
            val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
            if (vibrator.hasVibrator()) { // Vibrator availability checking
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    vibrator.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE)) // New vibrate method for API Level 26 or higher
                } else {
                    vibrator.vibrate(500) // Vibrate method for below API Level 26
                }
            }
        }
    }

}
Community
  • 1
  • 1
Avijit Karmakar
  • 8,890
  • 6
  • 44
  • 59
  • You create vibratorService with getSystemService, then your code doesn't use it. Instead, it uses something called vibrator, which you never created. I'm sure that's just a typo in your answer. – Octopus Dec 05 '18 at 22:12
  • VIBRATOR service is deprecated – Sadique Khan Mar 03 '22 at 19:02
5

Vibration using kotlin working sample try this

Manifest.xml

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

In kotlin:

 val vibratorService = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        vibratorService.vibrate(500)

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
>

    <Button
        android:id="@+id/btn_vibrate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Vibrate"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main);
        val btn_click_me = findViewById(R.id.btn_vibrate) as Button
        btn_click_me.setOnClickListener {
            val vibratorService = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
            vibratorService.vibrate(500)

        }
    }
}
Ramesh sambu
  • 3,577
  • 2
  • 24
  • 39
5

Vibrator Service is deprecated for API 31 and above. To do this the right way, do the following instead as addressed in this question:

 fun vibrate(){
    val vib = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        val vibratorManager =
            getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
        vibratorManager.defaultVibrator
    } else {
        @Suppress("DEPRECATION")
        getSystemService(VIBRATOR_SERVICE) as Vibrator
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        vib.vibrate(VibrationEffect.createOneShot(300, VibrationEffect.DEFAULT_AMPLITUDE) )
    }else{
        @Suppress("DEPRECATION")
        vib.vibrate(300)
    }
}
Chepech
  • 5,258
  • 4
  • 47
  • 70
2

Simplify it could be like

val buzzer = activity?.getSystemService<Vibrator>()

buzzer?.let {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                buzzer.vibrate(VibrationEffect.createWaveform(pattern, -1))
            } else {
                //deprecated in API 26
                buzzer.vibrate(pattern, -1)
            }
        }

When pattern could be like

val pattern = longArrayOf(0, 200, 100, 300)

Elements of buzzing and non-buzzing takes -> wait 0 ms, buzz 200ms, wait 100ms, buzz 300ms

Of course with permission in Manifest

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

Hope, it will help somebody in future

Developer534255
  • 121
  • 1
  • 9
0

To make your phone vibrate when a button is pushed, you can use the Vibrator class in Android. Here's how you can create a function to vibrate the device:

In Kotlin:

@Suppress("DEPRECATION")
    fun Context.vibrator(durationMillis: Long = 50) {
        when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
                // For Android 12 (S) and above
                val vibratorManager = getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
                val vibrationEffect = VibrationEffect.createOneShot(durationMillis, VibrationEffect.DEFAULT_AMPLITUDE)
                val vibrator = vibratorManager.defaultVibrator
                vibrator.vibrate(vibrationEffect)
            }

            Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && Build.VERSION.SDK_INT < Build.VERSION_CODES.S -> {
                // For Android 8.0 (Oreo) to Android 11 (R)
                val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
                val vibrationEffect = VibrationEffect.createOneShot(durationMillis, VibrationEffect.DEFAULT_AMPLITUDE)
                vibrator.vibrate(vibrationEffect)
            }

            else -> {
                // For Android versions below Oreo (API level 26)
                val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
                vibrator.vibrate(durationMillis)
            }
        }
    }

In the vibrator() function, the code is divided into three sections: one for Android 12 (S) and above, another for Android 8.0 (Oreo) to Android 11 (R), and the last one for versions below Oreo (API level 26).

Make sure to adjust the behavior and vibration duration according to your needs in each section.


Also, don't forget to add the necessary permissions in your AndroidManifest.xml file to use the vibrator:

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

To use this function, you can call it when the button is clicked.

in the Activity classes

myButton.setOnClickListener {
    vibrator(1000) // Vibrate for 1 second (1000 milliseconds)
}

or

myButton.setOnClickListener {
    vibrator() // Vibrate for 50 milliseconds
}

in the non Activity classes

myButton.setOnClickListener {
    context.vibrator(1000) // Vibrate for 1 second (1000 milliseconds)
}

or

myButton.setOnClickListener {
    context.vibrator() // Vibrate for 50 milliseconds
}
Masoud
  • 1
  • 2