(注意:本文基于UI Automator测试框架版本为2.2.0、UiAutomation的API版本为28)
UiDevice对象并没有直接持有UiAutomation对象,而是借助持有的Instrumentation对象,去获取UiAutomation对象,并使用它提供的功能,正式介绍UiAutomation对象之前,先看下UiDevice中对于UiAutomation对象的使用情况
UiDevice对象是通过它内部定义的一个静态方法getUiAumatation()获取一个UiAutomation对象,共计10处使用了UiAutomation对象提供的功能,涉及到获取屏幕信息、执行等待操作、设置压缩View树功能、还有屏幕更新等等功能,不过今天我们暂时不分析这些功能,只是分析一下UiAutomation对象是在哪里被创建的!
1、getUiAutomation方法,位于UiDevice类中
UiAutomation getUiAutomation() {
return getUiAutomation(getInstrumentation());
}
2、重载的getUiAutomation方法,同样位于UiDevice类中
static UiAutomation getUiAutomation(final Instrumentation instrumentation) {
int flags = Configurator.getInstance().getUiAutomationFlags();
if (UiDevice.API_LEVEL_ACTUAL > Build.VERSION_CODES.M) {
return instrumentation.getUiAutomation(flags);
} else {
// Custom flags not supported prior to N.
if (flags != Configurator.DEFAULT_UIAUTOMATION_FLAGS) {
Log.w(LOG_TAG, "UiAutomation flags not supported prior to N - ignoring.");
}
return instrumentation.getUiAutomation();
}
}
3、实际API版本的不同,获取UiAutomation的方法也不同
4、不管哪个API,最终都是从位于Instrumentation类中的getUiAutomation方法获取的UiAutomation对象
public UiAutomation getUiAutomation(@UiAutomationFlags int flags) {
boolean mustCreateNewAutomation = (mUiAutomation == null) || (mUiAutomation.isDestroyed());
if (mUiAutomationConnection != null) {
if (!mustCreateNewAutomation && (mUiAutomation.getFlags() == flags)) {
return mUiAutomation;
}
if (mustCreateNewAutomation) {
mUiAutomation = new UiAutomation(getTargetContext().getMainLooper(),
mUiAutomationConnection);
} else {
mUiAutomation.disconnect();
}
mUiAutomation.connect(flags);
return mUiAutomation;
}
return null;
}