【发布时间】:2023-03-16 02:33:01
【问题描述】:
我编写了一个 Android 应用程序。现在,我想让设备在某个动作发生时振动。我该怎么做?
【问题讨论】:
标签: java android kotlin vibration android-vibration
我编写了一个 Android 应用程序。现在,我想让设备在某个动作发生时振动。我该怎么做?
【问题讨论】:
标签: java android kotlin vibration android-vibration
试试:
import android.os.Vibrator;
...
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
//deprecated in API 26
v.vibrate(500);
}
注意:
不要忘记在 AndroidManifest.xml 文件中包含权限:
<uses-permission android:name="android.permission.VIBRATE"/>
【讨论】:
vibrate(VibrationEffect)。
在您开始实施任何振动代码之前,您必须为您的应用程序授予振动权限:
<uses-permission android:name="android.permission.VIBRATE"/>
确保在您的 AndroidManifest.xml 文件中包含这一行。
大多数 IDE 都会为您执行此操作,但如果您的 IDE 不这样做,这里是导入语句:
import android.os.Vibrator;
确保在您希望发生振动的活动中这样做。
在大多数情况下,您会希望在预定的短时间内振动设备。您可以使用vibrate(long milliseconds) 方法来实现此目的。这是一个简单的例子:
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 400 milliseconds
v.vibrate(400);
就是这样,简单!
您可能希望设备无限期地继续振动。为此,我们使用vibrate(long[] pattern, int repeat) 方法:
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Start without a delay
// Vibrate for 100 milliseconds
// Sleep for 1000 milliseconds
long[] pattern = {0, 100, 1000};
// The '0' here means to repeat indefinitely
// '0' is actually the index at which the pattern keeps repeating from (the start)
// To repeat the pattern from any other point, you could increase the index, e.g. '1'
v.vibrate(pattern, 0);
当您准备好停止振动时,只需调用cancel() 方法:
v.cancel();
如果您想要更定制的振动,您可以尝试创建自己的振动模式:
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Start without a delay
// Each element then alternates between vibrate, sleep, vibrate, sleep...
long[] pattern = {0, 100, 1000, 300, 200, 100, 500, 200, 100};
// The '-1' here means to vibrate once, as '-1' is out of bounds in the pattern array
v.vibrate(pattern, -1);
有多个 SDK 可提供更全面的触觉反馈。我用于特殊效果的一个是Immersion's Haptic Development Platform for Android。
如果您的设备不会振动,请先确保它可以振动:
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Output yes if can vibrate, no otherwise
if (v.hasVibrator()) {
Log.v("Can Vibrate", "YES");
} else {
Log.v("Can Vibrate", "NO");
}
其次,请确保您已授予应用程序振动的权限!回到第一点。
【讨论】:
Android-O(API 8.0) 已弃用 Update 2017 vibrate(interval) 方法
要支持所有 Android 版本,请使用此方法。
// Vibrate for 150 milliseconds
private void shakeItBaby() {
if (Build.VERSION.SDK_INT >= 26) {
((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(150);
}
}
科特林:
// Vibrate for 150 milliseconds
private fun shakeItBaby(context: Context) {
if (Build.VERSION.SDK_INT >= 26) {
(context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE))
} else {
(context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(150)
}
}
【讨论】:
getSystemService 替换为 this.getContext().getSystemService
以上答案很完美。但是,我想在按钮单击时准确地振动我的应用程序两次,而这里缺少这个小信息,因此为像我这样的未来读者发布。 :)
我们必须按照上面提到的方式进行,唯一的变化是振动模式如下,
long[] pattern = {0, 100, 1000, 300};
v.vibrate(pattern, -1); //-1 is important
这将准确地振动 两次。我们已经知道
人们可以交替提及延迟和振动(例如 0、100、1000、300、1000、300 表示 3 次振动等等),但请记住 @Dave 的话,负责任地使用它。 :)
另外请注意,repeat 参数设置为 -1,这意味着振动将发生完全如模式中所述。 :)
【讨论】:
如果您想简单地振动设备一次以提供有关用户操作的反馈。您可以使用View 的performHapticFeedback() 函数。这不需要在清单中声明VIBRATE 权限。
在您项目的 Utils.kt 等常见类中使用以下函数作为顶级函数:
/**
* Vibrates the device. Used for providing feedback when the user performs an action.
*/
fun vibrate(view: View) {
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
}
然后在Fragment 或Activity 中的任何位置使用它,如下所示:
vibrate(requireView())
就这么简单!
【讨论】:
在我的第一次实施中,我很难理解如何做到这一点 - 请确保您具备以下条件:
1) 您的设备支持振动(我的三星平板电脑无法正常工作,因此我不断重新检查代码 - 原始代码在我的 CM 触摸板上完美运行
2) 您已在 AndroidManifest.xml 文件中的应用程序级别上方声明,以授予代码运行权限。
3) 已将以下两项与其他导入一起导入您的 MainActivity.java: 导入android.content.Context; 导入android.os.Vibrator;
4) 调用您的振动(已在此线程中进行了广泛讨论) - 我在一个单独的函数中完成了它,并在其他点的代码中调用了它 - 取决于您想要使用什么来调用您可能需要图像的振动(Android: long click on a button -> perform actions) 或按钮侦听器,或 XML 中定义的可点击对象 (Clickable image - android):
public void vibrate(int duration)
{
Vibrator vibs = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibs.vibrate(duration);
}
【讨论】:
将它用作项目的某些通用类中的顶级函数,例如 Utils.kt
// 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)
}
}
}
然后在代码中的任意位置调用它,如下所示:
vibrateDevice(requireContext())
使用Vibrator::class.java 比使用String 常量更安全。
我们使用let { } 检查vibrator 的可空性,因为如果振动不适用于设备,vibrator 将是null。
可以在 else 子句中禁止弃用,因为警告来自较新的 SDK。
我们不需要在运行时请求许可才能使用振动。但我们需要在AndroidManifest.xml 中声明如下:
<uses-permission android:name="android.permission.VIBRATE"/>
【讨论】:
以模式/波形振动:
import android.os.Vibrator;
...
// Pause for 500ms, vibrate for 500ms, then start again
private static final long[] VIBRATE_PATTERN = { 500, 500 };
mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// API 26 and above
mVibrator.vibrate(VibrationEffect.createWaveform(VIBRATE_PATTERN, 0));
} else {
// Below API 26
mVibrator.vibrate(VIBRATE_PATTERN, 0);
}
加号
AndroidManifest.xml中的必要权限:
<uses-permission android:name="android.permission.VIBRATE"/>
【讨论】:
<uses-permission android:name="android.permission.VIBRATE"/>
应该添加在<manifest>标签内和<application>标签外。
【讨论】:
我使用以下 utils 方法:
public static final void vibratePhone(Context context, short vibrateMilliSeconds) {
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(vibrateMilliSeconds);
}
在AndroidManifest文件中添加以下权限
<uses-permission android:name="android.permission.VIBRATE"/>
如果您希望使用上面建议的不同类型的振动(模式/无限期),您可以使用重载方法。
【讨论】:
以上答案非常正确,但我给出了一个简单的步骤:
private static final long[] THREE_CYCLES = new long[] { 100, 1000, 1000, 1000, 1000, 1000 };
public void longVibrate(View v)
{
vibrateMulti(THREE_CYCLES);
}
private void vibrateMulti(long[] cycles) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification();
notification.vibrate = cycles;
notificationManager.notify(0, notification);
}
然后在你的xml文件中:
<button android:layout_height="wrap_content"
android:layout_width ="wrap_content"
android:onclick ="longVibrate"
android:text ="VibrateThrice">
</button>
这就是easiest 的方式。
【讨论】:
使用这个:
import android.os.Vibrator;
...
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 1000 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(1000,VibrationEffect.DEFAULT_AMPLITUDE));
}else{
//deprecated in API 26
v.vibrate(1000);
}
注意:
不要忘记在 AndroidManifest.xml 文件中包含权限:
<uses-permission android:name="android.permission.VIBRATE"/>
【讨论】:
您可以振动设备及其工作
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(100);
需要权限,但不需要运行时权限
<uses-permission android:name="android.permission.VIBRATE"/>
【讨论】: