清单文件
package com.ljq.activity;
import android.app.Activity;
import android.app.Service;
import android.os.Bundle;
import android.os.Vibrator;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class VibrateActivity extends Activity {
private Vibrator vibrator=null;
private ToggleButton tb1=null, tb2=null;
private TextView tv1=null, tv2=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//注意模拟器是模拟不了震动的,得真机测试哦
//创建vibrator对象
vibrator=(Vibrator)getSystemService(Service.VIBRATOR_SERVICE);
tv1=(TextView)findViewById(R.id.tv1);
tv2=(TextView)findViewById(R.id.tv2);
tb1=(ToggleButton)findViewById(R.id.tb1);
tb2=(ToggleButton)findViewById(R.id.tb2);
tb1.setOnCheckedChangeListener(listener);
tb2.setOnCheckedChangeListener(listener);
}
OnCheckedChangeListener listener=new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ToggleButton toggleButton=(ToggleButton)buttonView;
switch (toggleButton.getId()) {
case R.id.tb1:
if(isChecked){
//根据指定的模式进行震动
//第一个参数:该数组中第一个元素是等待多长的时间才启动震动,
//之后将会是开启和关闭震动的持续时间,单位为毫秒
//第二个参数:重复震动时在pattern中的索引,如果设置为-1则表示不重复震动
vibrator.vibrate(new long[]{1000,50,50,100,50}, -1);
tv1.setText("振动已启动");
}else {
//关闭震动
vibrator.cancel();
tv1.setText("震动已关闭");
}
break;
case R.id.tb2:
if(isChecked){
//启动震动,并持续指定的时间
vibrator.vibrate(3500);
tv2.setText("振动已启动");
}else {
//关闭启动
vibrator.cancel();
tv2.setText("震动已关闭");
}
break;
}
}
};
}
运行结果
注意:
private Vibrator vibrator;
取得震动服务的句柄
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
或者 vibrator = (Vibrator)getApplication().getSystemService(Service.VIBRATOR_SERVICE);
开始震动有两个接口
1 . vibrator.vibrate(2000);//震动指定时间 ,数据类型long,单位为毫秒,一毫秒为1/1000秒
2. vibrator.vibrate(new long[]{100,10,100,1000}, -1);//按照指定的模式去震动。
数组参数意义:第一个参数为等待指定时间后开始震动,震动时间为第二个参数。后边的参数依次为等待震动和震动的时间
第二个参数为重复次数,-1为不重复,0为一直震动
取消震动
vibrator.cancel();//取消震动,立即停止震动
震动为一直震动的话,如果不取消震动,就算退出,也会一直震动
最重要的,增加权限,否则运行时出错