Search code examples
androidandroid-vibration

Simulate API 29 Vibrations in 26 and below


I want to simulate API 29 vibration effects:

EFFECT_CLICK
EFFECT_DOUBLE_CLICK
EFFECT_HEAVY_CLICK
EFFECT_TICK

in version 26 and lower as well. Does anybody know how these translate?


Solution

  • Here is what I did. I am only covering two types of vibrations which will have to do. A longer single one and two short ones, which may translate to CLICK and DOUBLE_CLICK:

    private void vibrate(int vibrationMessageId) {
    
        long[] doubleClickPattern = {0, 75, 75, 75};
    
        if (Build.VERSION.SDK_INT >= 26) {
            Log.d(TAG, "vibrate: SDK 26+ " + Build.VERSION.SDK_INT);
    
            switch (vibrationMessageId) {
                case Constants.VIBRATION_HEAVY_CLICK:
                    ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE));
                    break;
                case Constants.VIBRATION_DOUBLE_CLICK:
                    ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createWaveform(doubleClickPattern,-1));
                    break;
            }
    
    
        } else {
            Log.d(TAG, "vibrate: SDK <26 " + Build.VERSION.SDK_INT);
    
            switch (vibrationMessageId) {
                case Constants.VIBRATION_HEAVY_CLICK:
                    ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(200);
                    break;
                case Constants.VIBRATION_DOUBLE_CLICK:
    
                    ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(doubleClickPattern,-1);
                    break;
            }
        }
    }