簡(jiǎn)介
android.os.Vibrator是Andoroid中負(fù)責(zé)震動(dòng)的類,是個(gè)系統(tǒng)級(jí)別,獲取對(duì)象的方法如下:
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
震動(dòng)和取消震動(dòng)
vibrator.vibrate(2000);
vibrator.cancel();
注意:震動(dòng)一定要加權(quán)限
<uses-permission android:name="android.permission.VIBRATE"/>
方法
| 方法 | 說(shuō)明 |
|---|---|
| vibrate (long milliseconds) | 觸發(fā)震動(dòng),參數(shù)是時(shí)長(zhǎng) |
| vibrate (long[] pattern, int repeat) | 觸發(fā)震動(dòng),參數(shù)下面在講 |
| cancel() | 取消震動(dòng) |
vibrate (long[] pattern, int repeat)
第一個(gè)參數(shù)是數(shù)組,其中的元素以此表示:震動(dòng)等待時(shí)長(zhǎng)+震動(dòng)時(shí)長(zhǎng);震動(dòng)等待時(shí)長(zhǎng)+震動(dòng)時(shí)長(zhǎng);震動(dòng)等待時(shí)長(zhǎng)+震動(dòng)時(shí)長(zhǎng);....
第二個(gè)參數(shù)有2種選擇:要么repeat=-1,要么repeat>=0;repeat=-1表示不重復(fù)震動(dòng);repeat>=0表示會(huì)一直震動(dòng),repeat的值表示數(shù)組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時(shí)只震動(dòng)一次;>=0時(shí):index,就是數(shù)組pattern中的索引;其中數(shù)組的長(zhǎng)度必須>1時(shí),repeat才有效。當(dāng)數(shù)組長(zhǎng)度為1時(shí),設(shè)置0是無(wú)效的。
} else {
vibrator.cancel();
}
}
});
其它#
還有一種觸摸按鍵引發(fā)手機(jī)震動(dòng)叫做“震動(dòng)反饋”,我在6.0手機(jī)中測(cè)試無(wú)效。
Android 無(wú)需權(quán)限即可觸發(fā)震動(dòng) HapticFeedback(震動(dòng)反饋)