如何让 Android 设备振动?频率不同?

新手上路,请多包涵

我写了一个 Android 应用程序。现在,我想让设备在特定动作发生时振动。我怎样才能做到这一点?

原文由 Billie 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 847
2 个回答

尝试:

 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"/>

原文由 Paresh Mayani 发布,翻译遵循 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题