Main interface Code:
Package Com.example.vibrator;import Android.app.activity;import Android.os.bundle;import android.view.View;import Android.view.view.onclicklistener;import Android.widget.button;public class Mainactivity extends Activity {private button Btn_vibrator_0;private button btn_vibrator_1; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); btn_vibrator_0 = (Button) findViewById ( R.ID.BTN_VIBRATOR_0) btn_vibrator_1 = (Button) Findviewbyid (r.id.btn_vibrator_1);/** * Click to set default vibration mode, Vibration 100 ms * */btn_ Vibrator_0.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated Method stub//Stop Shaking Vibratorutil.vibratecancel (mainactivity.this); Vibratorutil.vibrate (mainactivity.this,100); Vibration 100ms});/** * Click Set Custom vibration mode, repeat vibration * */btn_vibrator_1.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated method stub//Stop shaking Vibratorutil.vibratecancEl (Mainactivity.this);//Set vibration parameters, stop 50 milliseconds, shake 100 milliseconds long[] prams={50,100,50,100}; Vibratorutil.vibrate (mainactivity.this,prams,true); Vibration 100ms});} @Overrideprotected void OnDestroy () {//TODO auto-generated method Stubsuper.ondestroy ();// Stop shaking Vibratorutil.vibratecancel (mainactivity.this);}}
Vibration Function Module:
Package Com.example.vibrator;import Android.app.activity;import Android.app.service;import android.os.Vibrator;/** * Mobile phone Shake Tool class * * @author Administrator * */public class Vibratorutil {/** * Final activity activity: Invoke the method's activity instance * Lo ng milliseconds: the duration of the vibration, in milliseconds */public static void vibrate (final activity activity, long milliseconds) {Vibrator Vib = (VIB Rator) Activity.getsystemservice (Service.vibrator_service); vib.vibrate (milliseconds);} /** * Final activity activity: Invoke the method's activity instance * long[] Pattern: Custom vibrate mode. The meaning of the numbers in the array is [stationary duration, length of vibration, length of rest, duration of vibration ...] ] The length of the unit is milliseconds * Boolean isrepeat: Whether repeated vibrations, if true, repeated vibrations, if false, only vibrate once * */public static void vibrate (final activity activity, L Ong[] Pattern,boolean isrepeat) {Vibrator Vib = (vibrator) activity.getsystemservice (Service.vibrator_service); Vib.vibrate (Pattern, isrepeat? 1:-1);} /** * Stop shaking * */public static void Vibratecancel (final activity activity) {Vibrator Vib = (vibrator) Activity.getsystemservi CE (Service.vibrator_service); Vib.cancel ();}}
Example code address: http://download.csdn.net/detail/stop_pig/8213105
Android Vibration function