我正在尝试在触摸屏幕上的对象时使我的设备振动。 我正在使用这段代码:
Vibrator v = (Vibrator) getSystemService(getApplicationContext().VIBRATOR_SERVICE);
v.vibrate(300);
我在清单文件中添加了震动权限,但似乎没有效果。有什么建议吗?此外,我的硬件支持振动。
我正在尝试在触摸屏幕上的对象时使我的设备振动。 我正在使用这段代码:
Vibrator v = (Vibrator) getSystemService(getApplicationContext().VIBRATOR_SERVICE);
v.vibrate(300);
我在清单文件中添加了震动权限,但似乎没有效果。有什么建议吗?此外,我的硬件支持振动。
performHapticFeedback
方法。View view = findViewById(...)
view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
注意:我没有测试过这段代码。
请尝试这个:
Button b = (Button) findViewById(R.id.button1);
b.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vb.vibrate(100);
return false;
}
});
并将此权限添加到 manifest.xml 文件中。
<uses-permission android:name="android.permission.VIBRATE"/>
当用户触摸视图时,它会振动一次(当用户在视图上滑动手指时不会持续振动!):
@Override
public boolean onTouch(View view, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(VIBRATE_DURATION_MS);
}
return true;
}
正如Ramesh所说,在清单文件中允许权限:
<uses-permission android:name="android.permission.VIBRATE"/>
如果有人在寻找 kotlin
,
val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
vibrator.vibrator(durationInMilliSeconds)
对于Android O及更高版本,
val vibrationEffect = VibrationEffect.createOneShot(vibrationDuration, vibrationAmplitude)
vibrator.vibrator(vibrationEffect)
取消震动的同时,
vibrate.cancel()
你还需要在你的AndroidManifest.xml
中添加权限。
<uses-permission android:name="android.permission.VIBRATE"/>
对我有用的 kotlin ext fun
对于触觉效果,vibro有5毫秒!! (SHORT_HAPTIC_FEEDBACK_DURATION
)
fun Context.performHapticFeedback() {
val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val vibrationEffect = VibrationEffect.createOneShot(HAPTIC_FEEDBACK_DURATION, VibrationEffect.DEFAULT_AMPLITUDE)
vibrator.vibrate(vibrationEffect)
} else {
vibrator.vibrate(TimeUnit.MILLISECONDS.toMillis(SHORT_HAPTIC_FEEDBACK_DURATION))
}
}
private const val SHORT_HAPTIC_FEEDBACK_DURATION = 5L
用法
addOnItemTouchListener(ItemTouchListener { position, event ->
if (event.action == MotionEvent.ACTION_DOWN) {
context.performHapticFeedback()
}
})
权限
<uses-permission android:name="android.permission.VIBRATE"/>
祝你好运 ✌ :))