Android系统级服务:Vibrator

简介

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),如果不取消,即使app退出了,仍然会震动。
第一个参数是数组,其中的元素以此表示:震动等待时长+震动时长;震动等待时长+震动时长;震动等待时长+震动时长;….
第二个参数有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();
        }
    }
});

其它

Demo :http://git.oschina.net/AndroidBaseDemo/vibratedemo
还有一种触摸按键引发手机震动叫做“震动反馈”,我在6.0手机中测试无效。
Android 无需权限即可触发震动 HapticFeedback(震动反馈)

AudioAttributes audioAttributes = new AudioAttributes.Builder()
        .setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
        .setUsage(AudioAttributes.USAGE_GAME).build();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值