The vibrations in Android phones are implemented by vibrator. To set a vibration event, you need to know the length of the vibration, the period of vibration and so on.
In Android vibrator, the vibration time is calculated in milliseconds (1/1000 seconds), so if the set time value is too small, it will not feel.
Implemented by calling Vibrator's vibrate (long[] pattern, int repeat) method.
The previous parameter is an array of effects that set the vibration, and the second parameter is 1 for shaking only once, and for 0 the vibrations will persist.
A demo:
Package com.shao.vibrator;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.os.Vibrator;
Import Android.widget.CompoundButton;
Import Android.widget.Toast;
Import Android.widget.CompoundButton.OnCheckedChangeListener;
Import Android.widget.ToggleButton;
public class Vibratoractivity extends Activity {
Private vibrator Vibrator;
Private ToggleButton Tog1;
Private ToggleButton tog2;
Private ToggleButton Tog3;
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Init ();
Tog1.setoncheckedchangelistener (New Oncheckedchangelistener () {
@Override
public void OnCheckedChanged (Compoundbutton buttonview,
Boolean isChecked) {
TODO auto-generated Method Stub
if (isChecked) {
Set the vibration period
Vibrator.vibrate (New long[] {1000, 10, 100, 1000},-1);
Showtoast ("OK");
} else {
Remove vibrations
Vibrator.cancel ();
Showtoast ("Cancel");
}
}
});
Tog2.setoncheckedchangelistener (New Oncheckedchangelistener () {
@Override
public void OnCheckedChanged (Compoundbutton buttonview,
Boolean isChecked) {
TODO auto-generated Method Stub
if (isChecked) {
Set the vibration period
Vibrator.vibrate (new long[] {100, 100, 100, 1000}, 0);
Showtoast ("OK");
} else {
Remove vibrations
Vibrator.cancel ();
Showtoast ("Cancel");
}
}
});
Tog3.setoncheckedchangelistener (New Oncheckedchangelistener () {
@Override
public void OnCheckedChanged (Compoundbutton buttonview,
Boolean isChecked) {
TODO auto-generated Method Stub
if (isChecked) {
Set the vibration period
Vibrator.vibrate (New long[] {1000, 50, 1000, 50, 1000}, 0);
Showtoast ("OK");
} else {
Remove vibrations
Vibrator.cancel ();
Showtoast ("Cancel");
}
}
});
}
private void init () {
Tog1 = (ToggleButton) Findviewbyid (R.ID.TOG1);
TOG2 = (ToggleButton) Findviewbyid (R.ID.TOG2);
Tog3 = (ToggleButton) Findviewbyid (R.ID.TOG3);
Vibrator = (Vibrator) this.getsystemservice (Vibrator_service);
}
private void Showtoast (String msg) {
Toast.maketext (This, MSG, 1). Show ();
}
}
Xml:
Finally, don't forget to add <uses-permission android:name= "Android.permission.VIBRATE"/> Permissions.
This article is from the Interactive Infinite Network Technology Co., Ltd. www.hudongwx.com reprint please explain
Use of Android Vibrator