添加权限
在AndroidManifest.xml文件中添加如下震动权限
<uses-permission android:name="android.permission.VIBRATE"/>
获取Vibrator
vibrator = (Vibrator)context.getSystemService(this.VIBRATOR_SERVICE);
简单震动
先看下简单震动方法vibrate(long milliseconds)的源码
/**
* Vibrate constantly for the specified period of time.
*
* @param milliseconds The number of milliseconds to vibrate.
*
* @deprecated Use {@link #vibrate(VibrationEffect)} instead.
*/
@Deprecated
@RequiresPermission(android.Manifest.permission.VIBRATE)
public void vibrate(long milliseconds) {
vibrate(milliseconds, null);
}
使用方法很简单,就是传入一个毫秒值,手机会持续震动该毫秒值时长,震动完即停止
vibrator = (Vibrator)context.getSystemService(this.VIBRATOR_SERVICE);
vibrator.vibrate(1000); // 震动一秒
复杂震动
先看下复杂震动方法vibrate(long[] pattern, int repeat)的源码及注释说明
/**
* Vibrate with a given pattern.
*
* <p>
* Pass in an array of ints that are the durations for which to turn on or off
* the vibrator in milliseconds. The first value indicates the number of milliseconds
* to wait before turning the vibrator on. The next value indicates the number of milliseconds
* for which to keep the vibrator on before turning it off. Subsequent values alternate
* between durations in milliseconds to turn the vibrator off or to turn the vibrator on.
* </p><p>
* To cause the pattern to repeat, pass the index into the pattern array at which
* to start the repeat, or -1 to disable repeating.
* </p>
*
* @param pattern an array of longs of times for which to turn the vibrator on or off.
* @param repeat the index into pattern at which to repeat, or -1 if
* you don't want to repeat.
*
* @deprecated Use {@link #vibrate(VibrationEffect)} instead.
*/
@Deprecated
@RequiresPermission(android.Manifest.permission.VIBRATE)
public void vibrate(long[] pattern, int repeat) {
vibrate(pattern, repeat, null);
}
- 第一个参数pattern表示的是震动的模式,是一个long数组,表示的是震动和停止震动交替的时长,且第一个为停止震动的时长,第二个为震动的时长,第三个为停止震动的时长,以此类推。
- 第二个参数repeat表示从pattern中的第几个位置开始无限重复震动,若设置成-1则表示不重复震动
vibrator = (Vibrator)context.getSystemService(this.VIBRATOR_SERVICE);
long[] pattern = {100, 200, 100, 200}; // 100ms后开始震动200ms,然后再停止100ms,再震动200ms
vibrator.vibrate(pattern, 0); // 从pattern的0位置重复循环震动
若设置成重复震动需调用取消方法停止循环震动
vibrator.cancel();
来源:https://blog.csdn.net/mqdxiaoxiao/article/details/98959758