javaandroidaudioandroid-vibration

Android: How to make vibration work in "Vibrate" mode?


I have tried to make vibration on my app in Android (API 34, Android 11), with the following code:

Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        long[] pattern = {0, 500, 500};
        v.vibrate(VibrationEffect.createWaveform(pattern, 0));

When the device is in "Normal" mode (of the sound settings), the vibration is working, but when the device is in "Vibration Only", the vibration doesn't work.


Solution

  • To trigger a vibration in Jetpack Compose while respecting the device's sound profile (such as silent mode), you can use the AudioManager to check the current ringer mode before attempting to vibrate the device.

    val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
        if (audioManager.ringerMode != AudioManager.RINGER_MODE_SILENT) {
            val vibrator = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
                val vibratorManager = context.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
                vibratorManager.defaultVibrator
            } else {
                context.getSystemService(Vibrator::class.java)
            }
    
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                vibrator.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE))
            } else {
                vibrator.vibrate(500)
            }