Hit*_*ahu 40 android android-vibration android-8.0-oreo
我正在使用Android VIBRATOR_SERVICE来为按键触摸提供触觉反馈.
((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(300);
Run Code Online (Sandbox Code Playgroud)
Android Studio警告我vibrate(interval)不推荐使用该方法,我应该使用VibrationEffectAPI> 23.
所以我使用VibrationEffect的方法createOneShot需要2个参数:间隔和幅度.

我试着寻找它但却不知道要传递什么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);
}
}
Run Code Online (Sandbox Code Playgroud)
Aol*_*phn 11
与科特琳
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)
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将此用于触觉反馈(振动):
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
Run Code Online (Sandbox Code Playgroud)
还有在其他可用的常数HapticFeedbackConstants像VIRTUAL_KEY,KEYBOARD_TAP...
// Vibrates the device for 100 milliseconds.
fun vibrateDevice(context: Context) {
val vibrator = getSystemService(context, Vibrator::class.java)
vibrator?.let {
if (Build.VERSION.SDK_INT >= 26) {
it.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE))
} else {
@Suppress("DEPRECATION")
it.vibrate(100)
}
}
}
Run Code Online (Sandbox Code Playgroud)
调用函数如下:
vibrateDevice(requireContext())
Run Code Online (Sandbox Code Playgroud)
确保您向 AndroidManifest.xml 添加权限,如下所示:
<uses-permission android:name="android.permission.VIBRATE"/>
Run Code Online (Sandbox Code Playgroud)
请注意,使用振动不需要在运行时请求许可。
您需要禁止 inelse子句中的弃用,因为警告来自较新的 SDK。
我只是偶然发现了这个,发现它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)
}
}
Run Code Online (Sandbox Code Playgroud)
相反,VibrationEffect.createOneShot()您也可以使用模式(例如longArrayOf(0, 150)),因此无需使用不同的函数。
| 归档时间: |
|
| 查看次数: |
18478 次 |
| 最近记录: |