Vibrator可以控制手机的震动器,实现简单的持续震动以及周期振动。
布局XML代码不贴了,就一个ToggleButton.下面是JAVA代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | package com.pocketdigi.virbrate; import android.app.Activity; import android.app.Service; import android.os.Bundle; import android.os.Vibrator; import android.widget.CompoundButton; import android.widget.ToggleButton; import android.widget.CompoundButton.OnCheckedChangeListener; public class Main extends Activity { /** Called when the activity is first created. */ ToggleButton tb; Vibrator vt; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); vt=(Vibrator) getApplication().getSystemService(Service.VIBRATOR_SERVICE); //得到Vibrator对象 tb=(ToggleButton)findViewById(R.id.tb); tb.setOnCheckedChangeListener(new OnCheckedChangeListener(){ @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if(isChecked){ //vt.vibrate(1000); //最简单的震动,后面参数为振动持续的时间 long[] l=new long[]{1000,5000,2000,1000,1000,500}; //周期振动,索引0或偶数为间隔时间,索引为单数为振动时间(毫秒) vt.vibrate(l,1); //传入long数组,和重复振动开始的索引,这里是1,就是第二次执行的是{}这样一个数组 }else{ vt.cancel(); } } }); } } |
已经加了注释,不再解释。
还没有评论呢。
Powered by WordPress