UiAutomation injectInputEvent注入屏幕点击事件

//=========================================================================
//==                        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 received through the current Instrumentation
 */
@WorkerThread
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 当被设置为 true 的时候,只可在测试框架的子线程中调用,不可在被测试者的主线程(UI线程)中调用,否则会导致被测试UI线程阻塞。原因是调用之后需要在另一个线程中等待执行结果。

参考链接


How to inject click event with Android UiAutomation.injectInputEvent

发布者

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注