簡介
android.os.Vibrator
是Andoroid中負責震動的類,是個系統級別,獲取對象的方法如下:
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
震動和取消震動
vibrator.vibrate(2000);
vibrator.cancel();
注意:震動一定要加權限
<uses-permission android:name="android.permission.VIBRATE"/>
方法
方法 | 說明 |
---|---|
vibrate (long milliseconds) | 觸發震動,參數是時長 |
vibrate (long[] pattern, int repeat) | 觸發震動,參數下面在講 |
cancel() | 取消震動 |
vibrate (long[] pattern, int repeat)
第一個參數是數組,其中的元素以此表示:震動等待時長+震動時長;震動等待時長+震動時長;震動等待時長+震動時長;....
第二個參數有2種選擇:要么repeat=-1,要么repeat>=0;repeat=-1表示不重復震動;repeat>=0表示會一直震動,repeat的值表示數組pattern的索引
Demo
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ToastUtil.showShortToast(context, String.valueOf(isChecked));
if (isChecked) {
vibrator.vibrate(2000);
} else {
vibrator.cancel();
}
}
});
switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ToastUtil.showShortToast(context, String.valueOf(isChecked));
if (isChecked) {
long[] pattern = {1000, 2000};
int repeat = 0;
vibrator.vibrate(pattern, repeat);//repeat:-1時只震動一次;>=0時:index,就是數組pattern中的索引;其中數組的長度必須>1時,repeat才有效。當數組長度為1時,設置0是無效的。
} else {
vibrator.cancel();
}
}
});
其它#
還有一種觸摸按鍵引發手機震動叫做“震動反饋”,我在6.0手機中測試無效。
Android 無需權限即可觸發震動 HapticFeedback(震動反饋)