调用手机震动
Android中振动器(Vibrator)的使用
您 收的藏该 评经验 价:
系统获取Vibrator也是调用Context的getSystemService方法,接下来就可以调用Vibrator的方法控制手机振动了。Vibrator只有三个方法控制手机振动:
1、vibrate(long milliseconds):控制手机振动的毫秒数。 2、vibrate(long[] pattern,int repeat):指定手机以pattern模式振动,例如指定pattern为new long[]{400,800,1200,1600},就是指定在400ms、800ms、1200ms、1600ms这些时间点交替启动、关闭手机振动器,其中repeat指定pattern数组的索引,指定pattern数组中从repeat索引开始的振动进行循环。-1表示只振动一次,非-1表示从 pattern的指定下标开始重复振动。
3、cancel():关闭手机振动
下面通过一个示例来演示Vibrator的使用:
Activity:
01 importandroid.app.Activity;
02 importandroid.os.Bundle;
03 importandroid.os.Vibrator;
04 importandroid.widget.CompoundButton;
05 importandroid.widget.CompoundButton.OnCheckedChangeListener;
06 importandroid.widget.ToggleButton;
07
08 public class VibratorTestActivity extends Activity implements
09 OnCheckedChangeListener {
10 privateVibrator vibrator;
11 privateToggleButton tog1;
12 privateToggleButton tog2;
13 privateToggleButton tog3;
14 privateToggleButton tog4;
15
16 @Override
17 protected voidonCreate(Bundle savedInstanceState) {
18 super.onCreate(savedInstanceState);
19 setContentView(R.layout.activity_vibrator_test);
20 // 获取系统的Vibrator服务
21 vibrator = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
tog1 = (ToggleButton) 22 findViewById(R.id.activity_vibrator_test_tb1);
tog2 = (ToggleButton) 23 findViewById(R.id.activity_vibrator_test_tb2);
tog3 = (ToggleButton) 24 findViewById(R.id.activity_vibrator_test_tb3);
tog4 = (ToggleButton) 25 findViewById(R.id.activity_vibrator_test_tb4);
26 tog1.setOnCheckedChangeListener(this);
27 tog2.setOnCheckedChangeListener(this);
28 tog3.setOnCheckedChangeListener(this);
29 tog4.setOnCheckedChangeListener(this);
30
31 }
32
33 @Override
public void onCheckedChanged(CompoundButton buttonView, 34 booleanisChecked) {
35 if(isChecked) {
36 if(buttonView == tog1) {
37 // 设置震动周期
38 vibrator.vibrate(new long[] { 1000, 10, 100, 1000}, -1);
39 } else if(buttonView == tog2) {
40 vibrator.vibrate(new long[] { 100, 100, 100, 1000}, 0);
41 } else if(buttonView == tog3) {
vibrator.vibrate(new long[] { 1000, 50, 1000, 50, 1000}, 42 0);
43 } else if(buttonView == tog4) {
44 // 设置震动时长
45 vibrator.vibrate(5000);
46 }
47 } else{
48 // 关闭震动
49 vibrator.cancel();
50 }
51
52 }
53 }
布局XML:
查看源码
打印?
05
06
10
11
15
16
22
23
24
28
29
33
34
40
41
42
46
47
51
52
58
59
60
64
65
69
70
76
77
78