在测试中,可以对应设备(UiDevice)进行很多操作, 可以检测设备的各种属性,例如当前的屏幕方向以及屏幕尺寸;
同时还可以通过UiDevice实例来执行设备级别的操作,例如 把设备设置为横屏或者竖屏、按下Home按键等
这些操作的具体流程以及逻辑大同小异,以pressHome方法为例来论述其原理。
UiDevice 的pressHome方法如下,
public boolean pressHome() {
Tracer.trace();
waitForIdle();
return getAutomatorBridge().getInteractionController().sendKeyAndWaitForEvent(
KeyEvent.KEYCODE_HOME, 0, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED,
KEY_PRESS_EVENT_TIMEOUT);
}
getAutomatorBridge方法返回UiAutomatorBridge对象,如下,
UiAutomatorBridge getAutomatorBridge() {
if (mUiAutomationBridge == null) {
throw new RuntimeException("UiDevice not initialized");
}
return mUiAutomationBridge;
}
ShellUiAutomatorBridge对象在UiAutomatorTestRunner的start方法中创建并赋值给UiDevice的变量mUiAutomationBridge
mUiDevice = UiDevice.getInstance();
mUiDevice.initialize(new ShellUiAutomatorBridge(automationWrapper.getUiAutomation()));
很明显, UiDevice是一个单例,其initialize方法如下,
public void initialize(UiAutomatorBridge uiAutomatorBridge) {
mUiAutomationBridge = uiAutomatorBridge;
}
ShellUiAutomatorBridge继承于UiAutomatorBridge。UiAutomatorBridge中的getInteractionController方法如下,
InteractionController getInteractionController() {
return mInteractionController;
}
获取的是InteractionController对象,在UiAutomatorBridge的构造方法中实例化,
UiAutomatorBridge(UiAutomation uiAutomation) {
mUiAutomation = uiAutomation;
mInteractionController = new InteractionController(this);
mQueryController = new QueryController(this);
}
InteractionController的sen