系統獲取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>}
}