Vibration on button click not working in Android Studio

469 Views Asked by At

I want to add vibration functionality to my app and just wanted to get started with a simple vibration, I tried lots od turtorias but none of them seemed to work

@SuppressLint("NewApi")
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val timer_button = findViewById<Button>(R.id.timer_button)
    val timer_text: EditText = findViewById<EditText>(R.id.time_text)
    val vibrator  = getSystemService(VIBRATOR_MANAGER_SERVICE) as VibratorManager

   timer_button.setOnClickListener {
       //val pattern = longArrayOf(0, 200, 100, 300)
       vibrator.getDefaultVibrator().vibrate(VibrationEffect.createOneShot(1000,VibrationEffect.DEFAULT_AMPLITUDE))
       Toast.makeText(this, vibrator.getDefaultVibrator().getId().toString(),Toast.LENGTH_SHORT).show()

   }}

Also I added the vibration permission to my manifest.xml

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

There are 1 best solutions below

0
Rahimian On

It works in all APIS

val vibration = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            val vbManager =
                getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
            vbManager.defaultVibrator
        } else {
            @Suppress("DEPRECATION")
            getSystemService(VIBRATOR_SERVICE) as Vibrator
        }
        if (vibration.hasVibrator()) {
            vibration.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE))
        }