uiautomator一个简单的脚本
public class UiautomatorTest extends UiAutomatorTestCase{
public void testDemo() throws UiObjectNotFoundException {
// 模拟 HOME 键点击事件
getUiDevice().pressHome();
}
1、uiautomatorTest继承于UiAutomatorTestCase,通过父类获得Uidevice类实例,并调用父类方法pressHome();
2、查看pressHome方法源码
/**
* Simulates a short press on the HOME button.
* @return true if successful, else return false
* @since API Level 16
*/
public boolean pressHome() {
Tracer.trace();
waitForIdle();
return getAutomatorBridge().getInteractionController().sendKeyAndWaitForEvent(
KeyEvent.KEYCODE_HOME, 0, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED,
KEY_PRESS_EVENT_TIMEOUT);
}
getAutomatorBridge()方法获得InstrumentationUiAutomatorBridge实例,UiDevice类保存了
UiAutomatorBridge对象
InstrumentationUiAutomatorBridge getAutomatorBridge() {
if (mUiAutomationBridge == null) {
throw new RuntimeException("UiDevice not initialized");
}
return mUiAutomationBridge;
}
- 通过UiAutomatorBridge对象获得InteractionController对象
- 调用InteractionController对象的sendKeyAndWaitForEvent方法,里面参数关键是第一个keycode和第二个eventType
3、先来看下UiAutomatorBridge类何时初始化的还有InteractionController对象又是什么?
/**
* @hide
*/
public void initialize(InstrumentationUiAutomatorBridge uiAutomatorBridge) {
mUiAutomationBridge = uiAutomatorBridge;
}
这个是隐藏的方法,初始化UiDevice类时直接传入UiAutomatorBridge对象,那么改函数何时执行尼?
查看源码发现这个函数是在UiDevice类里面调用的
/**
* Initializes this test case.
*
* @param params Instrumentation arguments.
*/
void initialize(Bundle params) {
mParams = params;
// check if this is a monkey test mode
String monkeyVal = mParams.getString("monkey");
if (monkeyVal != null) {
// only if the monkey key is specified,