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); // 設(shè)置Vibrate的震動周期 vibrator.vibrate(new long[]{1000,2000,3000,4000}, 0); Toast.makeText(VibrateActivity.this, "震動了", Toast.LENGTH_LONG).show(); } else{ } } }); } } android.os.Vibrate代表著手機的振動器。用法很簡單,通過getSystemService()方法獲取示例,然后調(diào)用vibrate方法便可以實現(xiàn)震動。 要使用該振動器必須在AndroidManifest.xml中指定權(quán)限<uses-permission android:name="android.permission.VIBRATE"></uses-permission>
發(fā)表評論