[英]Creating a vibrator for Android in Kotlin
I'm trying to add vibration effects to my Android game.我正在尝试为我的 Android 游戏添加振动效果。 I found some code that seems to work, but it's deprecated.
我发现了一些似乎可以工作的代码,但它已被弃用。 What's the current way to create and deploy a vibrator?
当前创建和部署振动器的方法是什么?
var vibrator:Vibrator = getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
vibrator.vibrate(createPredefined(EFFECT_CLICK))
}else{
vibrator.vibrate(50)
}
The parts that are showing up as deprecated are "VIBRATOR-SERVICE" and vibrate.vibrate(50).显示为已弃用的部分是“VIBRATOR-SERVICE”和 vibrate.vibrate(50)。
Step 1: Add permission to the AndroidMenifest.xml
第 1 步:为
AndroidMenifest.xml
添加权限
<uses-permission android:name="android.permission.VIBRATE" />
Step 2: You can use this function for vibration.步骤 2:您可以使用此 function 进行振动。
fun vibrate(ctx: Context?) {
if (ctx != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val vibratorManager =
ctx.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
val vibrator = vibratorManager.defaultVibrator
vibrator.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK))
} else {
val v = ctx.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
v.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK))
} else {
v.vibrate(200L)
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.