系统获取Vibrator也是调用Context的getSystemService方法,接下来就可以调用Vibrator的方法控制手机振动了。Vibrator只有三个方法控制手机振动:
1、vibrate(long milliseconds):控制手机振动的毫秒数。
2、vibrate(long[] pattern,int repeat):指定手机以pattern模式振动,例如指定pattern为new long[]{400,800,1200,1600},就是指定在400ms、800ms、1200ms、1600ms这些时间点交替启动、关闭手机振动器,其中repeat指定pattern数组的索引,指定pattern数组中从repeat索引开始的振动进行循环。-1表示只振动一次,非-1表示从pattern的指定下标开始重复振动。
3、cancel():关闭手机振动
下面通过一个示例来演示Vibrator的使用:
Activity:
// 获取系统的Vibrator服务
vibrator = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
}
// 设置震动周期
vibrator.vibrate(new long[] { 1000, 10, 100, 1000 }, -1);
vibrator.vibrate(new long[] { 100, 100, 100, 1000 }, 0);
vibrator.vibrate(new long[] { 1000, 50, 1000, 50, 1000 }, 0);
// 设置震动时长
vibrator.vibrate(5000);
} else {
// 关闭震动
vibrator.cancel();
}
}
<span style="white-space:pre"> </span>protected void toVibrator() {
<span style="white-space:pre"> </span>/*
<span style="white-space:pre"> </span> * 想设置震动大小可以通过改变pattern来设定,如果开启时间太短,震动效果可能感觉不到
<span style="white-space:pre"> </span> */
<span style="white-space:pre"> </span>Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
<span style="white-space:pre"> </span>vibrator.vibrate(200);//控制手机振动的200毫秒。
//<span style="white-space:pre"> </span>long[] pattern = { 100, 400, 100, 400 }; // 停止 开启 停止 开启
//<span style="white-space:pre"> </span>vibrator.vibrate(pattern, -1); // 重复两次上面的pattern 如果只想震动一次,index设为-1
<span style="white-space:pre"> </span>}
}