Android:Vibrator

簡(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)反饋)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容