我编写了一个Android应用程序。现在,当发生某些事件时,我希望使设备振动。我该怎么做?
我编写了一个Android应用程序。现在,当发生某些事件时,我希望使设备振动。我该怎么做?
尝试:
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"/>
在开始实施任何震动代码之前,您需要给您的应用程序授予震动权限:
<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的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");
}
其次,请确保您已经允许应用程序震动的权限!请参考第一点。
2017年更新:vibrate(interval)方法在Android-O(API 8.0)中已弃用
为了支持所有的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);
}
}
Kotlin:
// 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)
}
}
this.getContext().getSystemService
替换getSystemService
。 - DrMcCleod如果您想在用户执行某个操作时仅振动设备一次以提供反馈,您可以使用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())
就这么简单!
上面的回答非常完美。但是我想在按钮点击时确切地让我的应用程序振动两次,这里缺少这些小信息,因此发布给像我这样的未来读者。
我们必须按照上面提到的方式执行,唯一的变化将在以下振动模式中进行:
long[] pattern = {0, 100, 1000, 300};
v.vibrate(pattern, -1); //-1 is important
这会精确地振动两次。就像我们已经知道的那样:
可以继续交替提及延迟和振动(例如,0、100、1000、300、1000、300表示3次振动等),但记得@ Dave的话,要负责任地使用。:)
还要注意这里的repeat参数设置为-1,这意味着振动将以完全按照模式中描述的方式进行。:)
在我的第一次实现中,我遇到了困难-请确保你拥有以下内容:
1)您的设备支持振动(我的三星平板电脑不起作用,所以我不断重新检查代码-原始代码在我的CM Touchpad上完美运行)。
2)在AndroidManifest.xml文件中,在应用程序级别之前声明以授权代码运行。
3)将以下两个内容与其他导入项一起导入到MainActivity.java中: import android.content.Context; import android.os.Vibrator;
4)调用您的振动(如本主题中详细讨论),我将其放在一个单独的函数中,并在代码的其他地方调用该函数-根据您想要使用什么来调用振动,您可能需要一个图像(Android:长按按钮->执行操作)或按钮侦听器,或在XML中定义的可点击对象(可点击图像-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>
标记之外。
上面的答案非常正确,但我会给出一个简单的步骤来完成它:
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>
那是最简单的方式。链接
vibrate(VibrationEffect)
代替。 - Timo Bähr