- package cn.com.chenzheng_java;
- import android.app.Activity;
- import android.media.AudioManager;
- import android.os.Bundle;
- import android.os.Vibrator;
- import android.view.View;
- import android.widget.Toast;
- import android.widget.ToggleButton;
- public class VibrateActivity extends Activity {
- private ToggleButton button ;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.vibrate);
- button = (ToggleButton) findViewById(R.id.toggleButton1);
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Boolean flag = button.isChecked();
- if(flag){
- // 获取Vibrate对象
- Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
- // vibrator.vibrate(3000);
- // 设置Vibrate的震动周期
- vibrator.vibrate(new long[]{1000,2000,3000,4000}, 0);
- Toast.makeText(VibrateActivity.this, "震动了", Toast.LENGTH_LONG).show();
- }
- else{
- }
- }
- });
- }
- }
android.os.Vibrate代表着手机的振动器。用法很简单,通过getSystemService()方法获取示例,然后调用vibrate方法便可以实现震动。
要使用该振动器必须在AndroidManifest.xml中指定权限<uses-permission android:name="android.permission.VIBRATE"></uses-permission>