Android:Vibrator

简介

android.os.Vibrator是Andoroid中负责震动的类,是个系统级别,获取对象的方法如下:

Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);

震动和取消震动

vibrator.vibrate(2000);
vibrator.cancel();

注意:震动一定要加权限


方法

方法 说明
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(震动反馈)

你可能感兴趣的:(Android:Vibrator)