1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
//========================================================================= //== Utility Methods === //========================================================================= /** * Helper method injects a click event at a point on the active screen via the UiAutomation object. * @param x the x position on the screen to inject the click event * @param y the y position on the screen to inject the click event * @param automation a UiAutomation object rtreived through the current Instrumentation */ static void injectClickEvent(float x, float y, UiAutomation automation){ //A MotionEvent is a type of InputEvent. //The event time must be the current uptime. final long eventTime = SystemClock.uptimeMillis(); //A typical click event triggered by a user click on the touchscreen creates two MotionEvents, //first one with the action KeyEvent.ACTION_DOWN and the 2nd with the action KeyEvent.ACTION_UP MotionEvent motionDown = MotionEvent.obtain(eventTime, eventTime, KeyEvent.ACTION_DOWN, x, y, 0); //We must set the source of the MotionEvent or the click doesn't work. motionDown.setSource(InputDevice.SOURCE_TOUCHSCREEN); automation.injectInputEvent(motionDown, true); MotionEvent motionUp = MotionEvent.obtain(eventTime, eventTime, KeyEvent.ACTION_UP, x, y, 0); motionUp.setSource(InputDevice.SOURCE_TOUCHSCREEN); automation.injectInputEvent(motionUp, true); //Recycle our events back to the system pool. motionUp.recycle(); motionDown.recycle(); } |
此处需要注意,injectInputEvent 的第二个参数 sync 如果一次按键之后,响应的控件很多,会造成分发消息耗时很长,导致ANR,此时只要把同步参数调整为异步即可解决(传入 false)。
参考链接
How to inject click event with Android UiAutomation.injectInputEvent