如何在Android工具测试中停止并重新启动活动? [英] How to stop and restart an activity in an android instrumentation test?

查看:153
本文介绍了如何在Android工具测试中停止并重新启动活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个Android活动检测测试,该测试将停止(先按onPause(),然后按onStop()),然后重新启动当前活动.我尝试过

I'm trying to write an Android activity instrumentation test that stops (onPause(), then onStop()) and restarts the current activity. I tried

activity.finish();
activity = getActivity();

...但是似乎无法正常工作.

...but that doesn't seem to work properly.

测试的目的是断言表单数据在onPause()方法期间存储,并在onStart()方法期间重新读取.手动执行此操作可以正常工作,但测试失败,由此得出的结论是activity.finish()似乎是停止和重新启动活动的错误方法.

The goal of the test is to assert that form data is stored during the onPause() method and re-read during the onStart() method. It works when doing it manually, but the test fails, from which I draw the conclusion that activity.finish() seems to be the wrong way to stop and restart an activity.

编辑:我的主要问题似乎是同步问题.重新启动活动后,测试运行程序没有等待所有事件处理程序完成.以下行暂停测试执行,直到活动空闲:

My main problem seems to have been a synchronization issue. After restarting the activity, the test runner didn't wait for all event handlers to finish. The following line halts the test execution until the activity is idle:

getInstrumentation().waitForIdleSync()

除此之外,请查看已接受的答案,以获取有关生命周期的更有价值的信息.

Besides that, take a look at the accepted answer for more valuable information about the lifecycle.

推荐答案

通过调用(或触发屏幕方向更改):

By calling (or trigger a screen orientation change):

activity.finish(); // old activity instance is destroyed and shut down.
activity = getActivity(); // new activity instance is launched and created.

使活动经历整个娱乐生命周期:

Causing the activity go through the complete recreation life cycle:

onPause() -> onStop() -> onDestroy() -> onCreate()

您需要的是:

onPause() -> onStop() -> onRestart()

我最近公开了仪器API ,发现了很多有趣的活动生命周期触发方法callActivityOnXXX(),下面的单行代码应该很棘手:

I exposed the Instrumentation API recently and found plenty of interesting activity life cycle trigger method callActivityOnXXX(), the following single line of code should do the tricky:

MyActivity myActivity = getActivity();
// make activity falling into restart phase:
getInstrumentation().callActivityOnRestart(myActivity);

活动生命周期图引用官方开发指南:

Activity life cycle diagram quoting from official dev guide:

这篇关于如何在Android工具测试中停止并重新启动活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆