如何判断 Android Activity 何时完成加载?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2089489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how can you tell when an Android activity is finished loading?
提问by Derrick
I'm in the process of working on an automated test suite for our android app, and running into trouble waiting for activities to fully load. I can call getActivity, but just because it shows the activity that I'm hoping to see in my test doesn't always seem to mean that the activity's components are ready for use (fully loaded). Looking through the Activity API didn't turn anything up, and other methods seem too invasive and have spoiled the tests initial state. Does anyone know if there's a way to ask the app or the VM if the current activity is loaded?
我正在为我们的 android 应用程序开发自动化测试套件,但在等待活动完全加载时遇到了麻烦。我可以调用 getActivity,但仅仅因为它显示了我希望在我的测试中看到的活动并不总是意味着活动的组件已准备好使用(完全加载)。查看 Activity API 没有发现任何问题,其他方法似乎太具有侵入性并且破坏了测试的初始状态。有谁知道是否有办法询问应用程序或虚拟机当前活动是否已加载?
回答by Christopher Orr
As I mentioned in a comment, your view hierarchy should be working after your call to setContentView()
early in onCreate()
. I've never had any problems like this with any activity or test class..
正如我所提到的注释,你的视图层次应您的来电后的工作setContentView()
早在onCreate()
。我从来没有在任何活动或测试课上遇到过这样的问题..
I'm not sure this is of any help for this specific case, but in general you can determine when the UI event queue is empty by calling getInstrumentation().waitForIdleSync()
. That'll block until there's no more UI events to process.
我不确定这对这种特定情况有什么帮助,但通常您可以通过调用getInstrumentation().waitForIdleSync()
. 这将一直阻塞,直到没有更多的 UI 事件需要处理。
回答by Diego Torres Milano
If you create a setUp()
method like this in your test case extending ActivityInstrumentationTestCase2<MyActivity>
如果您setUp()
在测试用例扩展中创建这样的方法ActivityInstrumentationTestCase2<MyActivity>
@Override
protected void setUp() throws Exception {
super.setUp();
final MyActivity activity = getActivity();
tv1 = (EditNumber)activity.findViewById(resId1);
tv2 = (EditNumber)activity.findViewById(resId2);
}
your Activity will be fully operational and the layout loaded, demonstrated in this case by the fact that you can access the Views and its content
您的活动将完全运行并加载布局,在这种情况下,您可以访问视图及其内容
@SmallTest
public void testSimpleCreate() {
final MyActivity activity = getActivity();
assertNotNull(activity);
assertNotNull(tv1);
assertEquals("mystr1", tv1.getText().toString());
assertNotNull(tv1);
assertEquals("mystr2", tv2.getText().toString());
}