Packagecom.example.administrator.myapplication;ImportAndroid.content.Context;ImportAndroid.os.Bundle;ImportAndroid.os.Vibrator;Importandroid.support.v7.app.AppCompatActivity;Importandroid.view.MotionEvent;ImportAndroid.view.View;ImportAndroid.widget.TextView; Public classMainactivityextendsAppcompatactivityImplementsview.ontouchlistener{//Inherit Ontouchlistener interface@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); TextView TV=(TextView) Findviewbyid (R.ID.TXV); Tv.setontouchlistener ( This);//listening for touch event objects} @Override Public BooleanOnTouch (view view, Motionevent Motioneven) {//get the Vibrating objectVibrator vb =(Vibrator) Getsystemservice (Context.vibrator_service); //judging the state of touch if(motioneven.getaction () = =Motionevent.action_down) {Vb.vibrate (5000); }Else if(motioneven.getaction () = =motionevent.action_up) {Vb.cancel (); } return false; }}
Where the return value of Ontouch () indicates whether other touch events are handled during the event, if the return value is false, then the hand touches the text area and starts shaking, shaking for five seconds. And if the return value is true, the moment the finger is released, in response to the condition in the else if, stop shaking. If you keep pressing it, it will stop for five seconds.
Before you enable the vibration, you also need to register the Androidmanifest.xml in the vibration, otherwise it will be abnormal. The program hangs directly. The contents of the registration are as follows:
<?XML version= "1.0" encoding= "Utf-8"?><Manifestxmlns:android= "Http://schemas.android.com/apk/res/android" Package= "Com.example.administrator.myapplication"> <!--Register Vibrate permissions - <uses-permissionAndroid:name= "Android.permission.VIBRATE"></uses-permission> <ApplicationAndroid:allowbackup= "true"Android:icon= "@mipmap/ic_launcher"Android:label= "@string/app_name"Android:roundicon= "@mipmap/ic_launcher_round"Android:supportsrtl= "true"Android:theme= "@style/apptheme"> <ActivityAndroid:name=". Mainactivity "> <Intent-filter> <ActionAndroid:name= "Android.intent.action.MAIN" /> <categoryAndroid:name= "Android.intent.category.LAUNCHER" /> </Intent-filter> </Activity> </Application></Manifest>
Android Touch Vibrate