Mobile phone device vibration is a good way to feedback information to users, especially in game applications. To control device vibration, our application needs to be licensed, that is, add the following code to the androidmanifest. xml file:
<Uses-Permission Android: Name = "android. Permission. Vibrate"/>
Device vibration is implemented through the vibrator class. The code for getting this class instance is as follows:
String vibratorservice = context. vibrator_service; <br/> vibrator = (vibrator) getsystemservice (vibratorservice );
Call the vibrate function to start vibration. This function has two overload functions:
Void vibrate (long [] pattern, int repeat); <br/> void vibrate (long milliseconds );
The former uses a specified mode and number of repetitions as parameters, and the latter uses the number of milliseconds of vibration as parameters.
You can call the cancel function to cancel the vibration. Note that after you exit the vibration program, if you do not manually call the cancel function to cancel the vibration, the vibration will continue (if the vibration persists ), regardless of whether the application exits.
The functions implemented by the following simple program are as follows: 1 second after the program starts, 2 seconds after vibration, 4 seconds after vibration, 8 seconds after vibration, 16 seconds after vibration, and repetition.
Package HUST. iprai. asce1885; </P> <p> Import android. app. activity; <br/> Import android. content. context; <br/> Import android. OS. bundle; <br/> Import android. OS. vibrator; </P> <p> public class devicevibrationactivity extends activity {</P> <p> private vibrator = NULL; </P> <p>/** called when the activity is first created. */<br/> @ override <br/> Public void oncreate (bundle savedinstancestate) {<br/> super. oncreate (savedinstancestate); <br/> setcontentview (R. layout. main); </P> <p> string vibratorservice = context. vibrator_service; <br/> vibrator = (vibrator) getsystemservice (vibratorservice); </P> <p> long [] pattern = {1000,200 0, 4000,800 0, 16000 }; <br/> vibrator. vibrate (pattern, 0); </P> <p >}</P> <p> @ override <br/> protected void ondestroy () {<br/> super. ondestroy (); <br/> vibrator. cancel (); <br/>}< br/>}