温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android Vibrator的使用

发布时间:2020-07-19 00:50:25 来源:网络 阅读:506 作者:hudongwx 栏目:移动开发



Android手机中的震动由Vibrator实现。设置震动事件,需要知道其震动的时间长短、震动的周期等。


在Android Vibrator中,震动的时间一毫秒计算(1/1000秒),所以如果设置的时间值太小,会感觉不出来。


通过调用Vibrator的vibrate(long[] pattern, int repeat)方法实现。


前一个参数为设置震动的效果的数组,第二个参数为 -1表示只震动一次,为0则震动会一直持续。


一个demo:


package com.shao.vibrator;


import android.app.Activity;

import android.os.Bundle;

import android.os.Vibrator;

import android.widget.CompoundButton;

import android.widget.Toast;

import android.widget.CompoundButton.OnCheckedChangeListener;

import android.widget.ToggleButton;


public class VibratorActivity extends Activity {


private Vibrator vibrator;

private ToggleButton tog1;

private ToggleButton tog2;

private ToggleButton tog3;


@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

init();

tog1.setOnCheckedChangeListener(new OnCheckedChangeListener() {


@Override

public void onCheckedChanged(CompoundButton buttonView,

boolean isChecked) {

// TODO Auto-generated method stub

if (isChecked) {

// 设置震动周期

vibrator.vibrate(new long[] { 1000, 10, 100, 1000 }, -1);

showToast("OK");

} else {

// 取消震动

vibrator.cancel();

showToast("CANCEL");

}

}

});

tog2.setOnCheckedChangeListener(new OnCheckedChangeListener() {


@Override

public void onCheckedChanged(CompoundButton buttonView,

boolean isChecked) {

// TODO Auto-generated method stub

if (isChecked) {

// 设置震动周期

vibrator.vibrate(new long[] { 100, 100, 100, 1000 }, 0);

showToast("OK");

} else {

// 取消震动

vibrator.cancel();

showToast("CANCEL");

}

}

});

tog3.setOnCheckedChangeListener(new OnCheckedChangeListener() {


@Override

public void onCheckedChanged(CompoundButton buttonView,

boolean isChecked) {

// TODO Auto-generated method stub

if (isChecked) {

// 设置震动周期

vibrator.vibrate(new long[] { 1000, 50, 1000, 50, 1000 }, 0);

showToast("OK");

} else {

// 取消震动

vibrator.cancel();

showToast("CANCEL");

}

}

});


}


private void init() {

tog1 = (ToggleButton) findViewById(R.id.tog1);

tog2 = (ToggleButton) findViewById(R.id.tog2);

tog3 = (ToggleButton) findViewById(R.id.tog3);

vibrator = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);

}


private void showToast(String msg) {

Toast.makeText(this, msg, 1).show();

}

}


xml:

最后别忘了加上<uses-permission  android:name="android.permission.VIBRATE"/>权限。




本文出自互动无限网络科技有限公司www.hudongwx.com转载请说明


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI