我写了一个 Android 应用程序。现在,我想让设备在特定动作发生时振动。我怎样才能做到这一点?
原文由 Billie 发布,翻译遵循 CC BY-SA 4.0 许可协议
我写了一个 Android 应用程序。现在,我想让设备在特定动作发生时振动。我怎样才能做到这一点?
原文由 Billie 发布,翻译遵循 CC BY-SA 4.0 许可协议
在你开始实现任何振动代码之前,你必须给你的应用程序振动的权限:
<uses-permission android:name="android.permission.VIBRATE"/>
确保将此行包含在您的 AndroidManifest.xml 文件中。
大多数 IDE 会为你做这件事,但如果你的 IDE 没有,这里是 import 语句:
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 的 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");
}
其次,请确保您已授予您的应用程序振动权限!回到第一点。
原文由 Liam George Betsworth 发布,翻译遵循 CC BY-SA 3.0 许可协议
15 回答8.4k 阅读
8 回答6.2k 阅读
1 回答4k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
2 回答3.8k 阅读
3 回答1.7k 阅读✓ 已解决
尝试:
笔记:
不要忘记在 AndroidManifest.xml 文件中包含权限: