How to make an Android device vibrate?

后端 未结 13 1968
长发绾君心
长发绾君心 2020-11-22 15:47

I wrote an Android application. Now, I want to make the device vibrate when a certain action occurs. How can I do this?

13条回答
  •  借酒劲吻你
    2020-11-22 16:25

    Update 2017 vibrate(interval) method is deprecated with Android-O(API 8.0)

    To support all Android versions use this method.

    // Vibrate for 150 milliseconds
    private void shakeItBaby() {
        if (Build.VERSION.SDK_INT >= 26) {
            ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE));
        } else {
            ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(150);
        }
    }
    

    Kotlin:

    // Vibrate for 150 milliseconds
    private fun shakeItBaby(context: Context) {
        if (Build.VERSION.SDK_INT >= 26) {
            (context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE))
        } else {
            (context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(150)
        }
    }
    

提交回复
热议问题