0

In my settings menu i have used a switch when i turn it on i want every button in-app to vibrate and when i turn the switch off i want every button in-the app to not vibrate.

The following is the code i have tried so far.

    switch2!!.setOnCheckedChangeListener { buttonView, isChecked ->
        if (switch2!!.isChecked) {
switch2!!.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
        }
        else {
                vibrator.cancel()
            }
        }
Zoe
  • 27,060
  • 21
  • 118
  • 148

2 Answers2

0

You can do like this.

  1. Using SharedPreference . https://developer.android.com/training/data-storage/shared-preferences

  2. Once you stored the key, you can use the key at the other activity/fragment.

  3. At onCreate , you get the value from SharedPreference.

  4. You use variable to check it first before click the button.

  5. If yes, then vibrate it. Refer to this. https://stackoverflow.com/a/52990380/9346054

**Don't forget to declare at AndroidManifest as the refer above.

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

Example.

Here at onCreate

val vibe = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
val isVibrate = sharedPref.getInt(getString(R.string.is_vibrate), defaultValue)

And then inside onClick button

    if (isVisible) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            vibrator.vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE))
        } else {
            vibrator.vibrate(200)
        }
    }
Ticherhaz FreePalestine
  • 2,738
  • 4
  • 20
  • 46
0

you need to add this permission first

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

and next you can use this fun for vibrate mobile

fun vibratePhone(context: Context?, milliseconds: Int) {
    val vibrator = context?.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
    if (Build.VERSION.SDK_INT >= 26) {
        vibrator.vibrate(
            VibrationEffect.createOneShot(
                milliseconds,
                VibrationEffect.DEFAULT_AMPLITUDE
            )
        )
    } else {
        vibrator.vibrate(milliseconds)
    }
}
Mahdi Zareei
  • 1,299
  • 11
  • 18