Introduction
There are two ways to simulate a click event in Android by simulating the motionevent, and by using ADB to achieve
The first: The general method of analog motionevent is as follows:
private void Setsimulateclick (view view, float x, float y) {Long downtime = Systemclock.uptimemillis (); final Motionevent D Ownevent = Motionevent.obtain (Downtime, Downtime,motionevent.action_down, x, y, 0);d owntime + = 1000;final MotionEvent Upevent = Motionevent.obtain (Downtime, downtime,motionevent.action_up, x, y, 0); View.ontouchevent (downEvent); View.ontouchevent (upevent);d ownevent.recycle (); Upevent.recycle ();}
Demo:
Package Com.xys.simulateevent;import Android.app.activity;import Android.os.bundle;import android.os.SystemClock; Import Android.view.motionevent;import android.view.view;import android.widget.button;import android.widget.Toast; public class Mainactivity extends Activity {button button; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); button = (Button) Findviewbyid ( R.id.button1);} public void Clickeme (view view) {Toast.maketext (this, "clicked", Toast.length_long). Show (); public void simulate (view view) {Setsimulateclick (button, 160, 100);} private void Setsimulateclick (view view, float x, float y) {Long downtime = Systemclock.uptimemillis (); final Motionevent D Ownevent = Motionevent.obtain (Downtime, Downtime,motionevent.action_down, x, y, 0);d owntime + = 1000;final MotionEvent Upevent = Motionevent.obtain (Downtime, downtime,motionevent.action_up, x, y, 0); View.ontouchevent (downEvent); View.ontouchevent (UpevenT);d ownevent.recycle (); Upevent.recycle ();}}
The second type: ADB control adb is implemented by input, for inputTouch,key and other events:
The sources is: trackball joystick touchnavigation mouse keyboard gamepad Touchpad dpad Stylus touchscreenthe commands and default sources are: text <string> (default: touchscreen) KeyEvent [--longpress] <key code number or name> ... (Default:keyboard) Tap <x> <y> (default:touchscreen) swipe <x1> <y1> <x2> <y2> [Duration (ms)] ( Default:touchscreen) Press (default:trackball) Roll <dx> <dy> (Default:trackball)
Demo input Key enter key:
ADB shell Input KeyEvent 66
Demo Input input swipe operation:
ADB shell input touchscreen swipe 18 665 18 350