Android vibrate已弃用。如何在Android> = API 26中使用VibrationEffect?

问题描述 投票:31回答:6

我正在使用Android的VIBRATOR_SERVICE为按键触摸提供触觉反馈。

 ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(300);

Android Studio警告我不推荐使用vibrate(interval)方法我应该使用VibrationEffect for API> 23。

所以我使用VibrationEffect的方法createOneShot,它采用2个参数:间隔和振幅。 enter image description here

我试着寻找它,但不知道要传递什么作为amplitude,任何人都知道如何使用它?

更新添加的代码

// Vibrate for 150 milliseconds
private void shakeItBaby() {
    if (Build.VERSION.SDK_INT >= 26) {
        ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150,10));
    } else {
        ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(150);
    }
}
android android-vibration android-8.0-oreo
6个回答
16
投票

幅度是一个int值。它的振动强度。这必须是介于1和255之间的值,或DEFAULT_AMPLITUDE为-1。

你可以用它作为VibrationEffect.DEFAULT_AMPLITUDE

更多细节here


9
投票

用kotlin

private fun vibrate(){
    val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
         vibrator.vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE))
    } else {
         vibrator.vibrate(200)
    }
}

6
投票

您可以将此用于触觉反馈(振动):

view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);

HapticFeedbackConstants中还有其他常量,如VIRTUAL_KEYKEYBOARD_TAP ......


1
投票

这个图书馆可以帮您解决:https://github.com/josephrubin/Rumble-4-Android

所有你需要的是Rumble.once(150);

它为您处理API版本。


1
投票

我偶然发现了这一点,发现VibrationEffect.createWaveform()基本上使用与旧long[]相同的vibrate()模式。

因此,您可以像这样重用现有模式(这是Kotlin扩展函数):

fun Context.vibrate(pattern: LongArray) {
    val vibrator =
        applicationContext.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator? ?: return

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        vibrator.vibrate(
            VibrationEffect.createWaveform(pattern, VibrationEffect.DEFAULT_AMPLITUDE)
        )

    } else {
        @Suppress("DEPRECATION")
        vibrator.vibrate(pattern, -1)
    }
}

而不是VibrationEffect.createOneShot()你也可以使用一个模式(例如longArrayOf(0, 150)),所以不需要使用不同的功能。


0
投票

enter image description hereOpen管理NuGet包

搜索并安装Xamarin.Essentials

try {
 var duration = TimeSpan.FromMilliseconds(300);
 Vibration.Vibrate(duration);
} 
 catch (FeatureNotSupportedException ex){} 
 catch (Exception ex){}
© www.soinside.com 2019 - 2024. All rights reserved.