---
title: "手机震动设置"
author: "AndLi"
date: "2011-11-24T20:04:17Z"
tags: []
categories: ["移动开发"]
slug: "untitled"
draft: false
lastmod: "2011-11-24T20:05:34Z"
id: 1277117
url: "https://andli.iteye.com/blog/1277117"
---

```
public class Main extends Activity {
	Vibrator vibrator; // 声明一个Vibrator对象

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE); // 创建Vibrator对象
		((CompoundButton) findViewById(R.id.tb1))
				.setOnCheckedChangeListener(new OnCheckedChangeListener() { // 设置OnCheckedChangeListener监听器
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) { // 重写onCheckedChanged方法
						if (isChecked) { // 判断ToggleButton的选中状态
							vibrator.vibrate(
									new long[] { 1000, 50, 50, 100, 50 }, -1); // 启动振动
							TextView tv1 = (TextView) findViewById(R.id.tv1); // 获得TextView
							tv1.setText(R.string.vibrateOn); // 设置TextView控件内容
						} else {
							vibrator.cancel(); // 关闭振动
							TextView tv1 = (TextView) findViewById(R.id.tv1); // 获得TextView
							tv1.setText(R.string.vibrateOff); // 设置TextView控件内容
						}
					}
				});
		((CompoundButton) findViewById(R.id.tb2))
				.setOnCheckedChangeListener(new OnCheckedChangeListener() { // 设置OnCheckedChangeListener监听器
					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (isChecked) { // 判断ToggleButton的选中状态
							vibrator.vibrate(2500); // 启动振动
							((TextView) findViewById(R.id.tv2))
									.setText(R.string.vibrateOn);
						} else {
							vibrator.cancel(); // 关闭振动
							((TextView) findViewById(R.id.tv2))
									.setText(R.string.vibrateOff);
						}
					}
				});
	}
}
```

 &lt;uses-permission android:name="android.permission.VIBRATE" /&gt;

![](http://dl.iteye.com/upload/attachment/594686/6b333073-2b7a-3c2e-ae3c-f666526f8255.jpg)