public void takeScreenshot(){ View decorView = viewFetcher.getRecentDecorView(viewFetcher.getWindowDecorViews()); screenshotTaker.takeScreenshot(decorView, null);}
viewFetcher.getWindowDecorViews()用来获取当前屏幕上堆积的所有DecorView(可以把一个DecorView当做是一个画布,当你打开好多Activity时,相当于有好几个画布叠在了一起,每个画布上画着一个activity的画面)。而viewFetcher.getRecentDecorView()就相当于取最上一层的画布。进入ViewFetcher.java文件观察viewFetcher.getRecentDecorView()的源码,我发现它在排除了一些无用的view后,实际返回的是ViewFetcher.java中的另一个函数的结果:getRecentContainer(decorViews)。Be patient, 让我们看看getRecentContainer(decorViews)里卖的是什么药:
private final View getRecentContainer(View[] views) { View container = null; long drawingTime = 0; View view; for(int i = 0; i < views.length; i++){ view = views[i]; if (view != null && view.isShown() && view.hasWindowFocus() && view.getDrawingTime() > drawingTime) { container = view; drawingTime = view.getDrawingTime(); } } return container;}
getRecentContainer(decorViews)函数判断哪个view在最上层的方法,是判断:
- view不为空
view可见 - view已经被focus上(就是该view是否处于被选中的、被激活的窗口中)
- 渲染时间排在最后
public void takeScreenshot(){ View decorView = null;while(decorView == null){ sleep(500); View[] decorViews = viewFetcher.getWindowDecorViews(); decorView = viewFetcher.getRecentDecorView(decorViews);}screenshotTaker.takeScreenshot(decorView, null);}
https://code.google.com/p/robotium/issues/detail?id=434&colspec=ID%20Type%20Stars%20Status%20Priority%20Milestone%20Owner%20Summary
Solo.java中添加:
public void assertCurrentActivity(String message, String name, int timeout, boolean takeScreenshot){ if(takeScreenshot){ asserter.assertCurrentActivity(message, name, timeout, this); } else assertCurrentActivity(message, name, timeout);}Asserter.java中添加:
public void assertCurrentActivity(String message, String name, int timeout, Solo solo){ if(!waiter.waitForActivity(name, timeout)){ solo.takeScreenshot("test_" + message + "Failure"); Assert.assertTrue(message, false); } else solo.takeScreenshot("test" + message + "_Success"); }
****我曾经在《结合HierarchyViewer和APK文件反编译获得APP元素id值》一文中非常SB地写了出了如何通过HierarchyViewer里的id名获得元素的id整型值。现在,我知道了新的方法,会结合HierarchyViewer来进行自动化测试的人民有福了:****Solo.java中添加:
public View getViewByHierarchyViewerId(String id){ Context currContext = instrumentation.getTargetContext(); String packageName = currContext.getPackageName(); int viewId = currContext.getResources().getIdentifier(id, "id", packageName); return getView(viewId);