如何让安卓设备以不同频率振动?

602

我编写了一个Android应用程序。现在,当发生某些事件时,我希望使设备振动。我该怎么做?

14个回答

1125

尝试:

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

3
有没有一种方法可以取消手机的所有震动?谢谢! - Javi
15
500毫秒就是半秒钟。请查看Google文档。http://developer.android.com/reference/android/os/Vibrator.html - cjayem13
6
提示信息为:"context cannot be resolved or is not a field",意思是上下文无法解析或不是一个字段。出现了什么问题? - McLan
3
振动功能现已过时。请改用Hitesh Sahu的解决方案。 - Ray Li
3
此方法已在API级别26中弃用。使用vibrate(VibrationEffect)代替。 - Timo Bähr
显示剩余2条评论

703

授予震动权限

在开始实施任何震动代码之前,您需要给您的应用程序授予震动权限:

<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");
}

其次,请确保您已经允许应用程序震动的权限!请参考第一点。


32
回答很好,不过我建议谨慎使用震动功能,不要无限制地使用。请在使用该功能时保持责任心! - Dave
6
回答很好,但有一点需要注意。当你说“这里的 '0' 意味着无限重复”,虽然是正确的,但有点误导。这个数字是模式数组中模式开始重复的索引。 - aaronvargas
1
@aaronvargas 说得很好,不过这超出了大多数人想要实现的范围。我选择了简单的解释 :) - Liam George Betsworth
@Dave,因为我不得不强制关闭我的应用程序 :) - Muhammad Saqib
1
沉浸式链接已经失效,我在archive.org上也找不到它 :( - looper
显示剩余7条评论

110

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)
    }
}

3
我们不需要运行时权限来控制手机震动。震动并不是一种危险权限,所以我们只需要在清单文件中声明即可。[https://developer.android.com/guide/topics/permissions/normal-permissions.html](来源) - Roon13
@BugsHappen 的文档已移动。将进行更新或删除。 - Roon13
我唯一要补充的是,如果您将其用于Activity并且没有特定的Context变量,则请用this.getContext().getSystemService替换getSystemService - DrMcCleod
19
因为那个函数名,你赢得了我的点赞,太棒了。 - Starwave

37

无需使用权限振动

如果您想在用户执行某个操作时仅振动设备一次以提供反馈,您可以使用ViewperformHapticFeedback()函数。这不需要在清单文件中声明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)
}

然后可以在您的FragmentActivity中按照以下方式随处使用它:

vibrate(requireView())

就这么简单!


5
确保添加HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING标志,以便它在所有设备上都能正常工作。 - G00fY

32

上面的回答非常完美。但是我想在按钮点击时确切地让我的应用程序振动两次,这里缺少这些小信息,因此发布给像我这样的未来读者。

我们必须按照上面提到的方式执行,唯一的变化将在以下振动模式中进行:

long[] pattern = {0, 100, 1000, 300};
v.vibrate(pattern, -1); //-1 is important

这会精确地振动两次。就像我们已经知道的那样:

  1. 0表示延迟
  2. 100表示第一次振动持续100毫秒
  3. 接下来是延迟1000毫秒
  4. 之后再振动300毫秒

可以继续交替提及延迟振动(例如,0、100、1000、300、1000、300表示3次振动等),但记得@ Dave的话,要负责任地使用。:)

还要注意这里的repeat参数设置为-1,这意味着振动将以完全按照模式中描述的方式进行。:)


为什么-1意味着振动会完全按照模式中提到的方式发生?谢谢! - Ruchir Baronia
@Rich 请参考我的回答。‘-1’是振动在第一次按照模式后尝试从哪个索引重复的位置。因为‘-1’超出了边界,所以振动不会重复。 - Liam George Betsworth
@Rich - Liam George Betsworth是正确的。Android文档中指出,要使模式重复,需要传递模式数组中开始重复的索引,或者传递-1来禁用重复。链接 - http://developer.android.com/reference/android/os/Vibrator.html#vibrate(long[], int) - Atul O Holic

14

在我的第一次实现中,我遇到了困难-请确保你拥有以下内容:

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);    
 }

14

增加类型安全性的 Kotlin 更新

在您的项目中的某些常见类,例如 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"/>

13

模式/波浪振动:

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

2
实际上,它会暂停500毫秒,震动500毫秒,然后重新开始。 - Ridcully

5
<uses-permission android:name="android.permission.VIBRATE"/>

应添加在<manifest>标记内,但在<application>标记之外。


4

上面的答案非常正确,但我会给出一个简单的步骤来完成它:

 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>

那是最简单的方式。链接


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接