【发布时间】:2013-07-30 07:59:27
【问题描述】:
有没有人知道如何通过uiautomator 代码拨打am start -a ACTIVITY。
或者是否可以直接从junit 代码开始活动。
【问题讨论】:
标签: android android-uiautomator
有没有人知道如何通过uiautomator 代码拨打am start -a ACTIVITY。
或者是否可以直接从junit 代码开始活动。
【问题讨论】:
标签: android android-uiautomator
这是我用来从 .jar 文件启动活动的示例:
private boolean startSettings() {
try {
Runtime.getRuntime().exec(
"am start -n com.android.settings/.Settings");
sleep(1000);
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < 5; i++) {
sleep(1000);
if (getUiDevice().getCurrentPackageName().contains(
"com.android.settings")) {
return true;
}
}
return false;
}
您可以修改代码以启动任何应用程序。您还可以通过为包/活动值添加参数来使该方法更通用。
【讨论】:
com.app.myapp/.MainActivity 不工作。完全限定名称也不起作用。但是从命令提示符adb shell am start -n com.app.myapp/.MainActivity 有什么想法吗?
应该是下面的代码。我在测试中使用它。
UiDevice device = UiDevice.getInstance(getInstrumentation());
final String TARGET_PACKAGE =
InstrumentationRegistry.getTargetContext().getPackageName();
Context context = InstrumentationRegistry.getContext();
final Intent intent = context.getPackageManager().getLaunchIntentForPackage(TARGET_PACKAGE);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
device.wait(Until.hasObject(By.pkg(TARGET_PACKAGE).depth(0)), 5000);
【讨论】:
我所做的是将启动应用程序和运行 UIAutomator 测试作为构建的一部分。这就是我在构建 Ant build.xml 后运行 UIAutomator 测试的方式。这个 sn-p 添加到 build.xml 的末尾并导致您的应用程序启动,然后启动您的 UI 测试。使用 eclipse 确保你右键单击 build.xml 然后 -> Run As -> Ant Build... 并确保选择了正确的目标:'build'、'install'、'start'、'mytest'。目标 'start' 和 'mytest' 通过以下 sn-p 添加。
<!-- version-tag: VERSION_TAG -->
<!-- This line should already be at the end of build.xml -->
<import file="${sdk.dir}/tools/ant/uibuild.xml" />
<target name="start" description="Start App" depends="build, install">
<echo>Starting Navigation Example</echo>
<exec executable="${adb}" failonerror="true">
<arg value="shell" />
<arg value="am" />
<arg value="start" />
<arg value="-n" />
<arg value="com.example.android.navigationdrawerexample/.MainActivity" />
</exec>
</target>
<target name="mytest" description="Runs UI tests" depends="build, install, start">
<echo>Running UI Tests</echo>
<exec executable="${adb}" failonerror="true">
<arg value="shell" />
<arg value="uiautomator" />
<arg value="runtest" />
<arg value="${out.filename}" />
<arg value="-c" />
<arg value="com.example.android.navigationdrawerexample.MainTestCase" />
</exec>
</target>
【讨论】: