Android 如何在触摸应用程序中的每个按钮时启用振动
在我的设置菜单中,当我打开开关时,我希望应用程序中的每个按钮都振动,当我关闭开关时,我希望应用程序中的每个按钮都不振动 以下是我迄今为止尝试过的代码Android 如何在触摸应用程序中的每个按钮时启用振动,android,kotlin,vibration,Android,Kotlin,Vibration,在我的设置菜单中,当我打开开关时,我希望应用程序中的每个按钮都振动,当我关闭开关时,我希望应用程序中的每个按钮都不振动 以下是我迄今为止尝试过的代码 switch2!!.setOnCheckedChangeListener { buttonView, isChecked -> if (switch2!!.isChecked) { switch2!!.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
switch2!!.setOnCheckedChangeListener { buttonView, isChecked ->
if (switch2!!.isChecked) {
switch2!!.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
}
else {
vibrator.cancel()
}
}
你可以这样做
SharedReference
onCreate
,您可以从SharedReference
获取值
AndroidManifest
中声明,如上所述
<uses-permission android:name="android.permission.VIBRATE" />
然后在内单击按钮
if (isVisible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE))
} else {
vibrator.vibrate(200)
}
}
您需要先添加此权限
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.VIBRATE"/>
fun vibratePhone(context: Context?, milliseconds: Int) {
val vibrator = context?.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
if (Build.VERSION.SDK_INT >= 26) {
vibrator.vibrate(
VibrationEffect.createOneShot(
milliseconds,
VibrationEffect.DEFAULT_AMPLITUDE
)
)
} else {
vibrator.vibrate(milliseconds)
}
}