模拟API 29振动26及以下

Simulate API 29 Vibrations in 26 and below

我要模拟API29种震动效果:

EFFECT_CLICK
EFFECT_DOUBLE_CLICK
EFFECT_HEAVY_CLICK
EFFECT_TICK

在版本 26 及更低版本中也是如此。有人知道这些怎么翻译吗?

或多或少h/w兼容。

这里有 2 件事,

  1. VibrationEffect 已添加到 Api 级别 26 https://developer.android.com/reference/android/os/VibrationEffect

  2. 振动器已从 Api 级别 26 开始弃用,VibrationEffect 开始发挥作用,如上所述 https://developer.android.com/reference/android/os/Vibrator.html#vibrate(long%5B%5D,%20int)

这是我所做的。我只涉及两种必须要做的振动。较长的单个和两个较短的,可以转换为 CLICK 和 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;
        }
    }
}