- boolean hasVibrator(): 檢查硬件是否有震動器. (API Level 11)
- void vibrate(long milliseconds): 開啟振動器.
- void vibrate(long[] pattern, int repeat): 按模式振動.
- void cancel(): 取消振動.
實例:
package com.AndroidVibrator;
import android.app.Activity;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class AndroidVibratorActivity extends Activity {
long[] vibratepattern = {100, 400, 500};
Vibrator vibrator;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
vibrator = (Vibrator)getSystemService(
AndroidVibratorActivity.VIBRATOR_SERVICE);
Button startVibrate = (Button)findViewById(R.id.startvibrate);
startVibrate.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
vibrator.vibrate(vibratepattern, 0);
}});
Button stopVibrate = (Button)findViewById(R.id.stopvibrate);
stopVibrate.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
vibrator.cancel();
}});
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/startvibrate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start Vibrate" />
<Button
android:id="@+id/stopvibrate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Stop Vibrate" />
</LinearLayout>
使用 android.os.Vibrator (振動器), 需要修改 AndroidManifest.xml 添加 "android.permission.VIBRATE" 權限.

沒有留言:
發佈留言