Android UIAutomator的UiWatcher示例无法正常工作

时间:2013-07-23 18:10:37

标签: uiautomator

  

import com.android.uiautomator.core.UiObject;       import com.android.uiautomator.core.UiObjectNotFoundException;       import com.android.uiautomator.core.UiSelector;       import com.android.uiautomator.core.UiWatcher;       import com.android.uiautomator.testrunner.UiAutomatorTestCase;

public class uiWatcherDemo extends UiAutomatorTestCase {

  private static final String NOINTERNET_STRING = "InternetWatcher";

  public void testWatcherDemoTestExample() throws UiObjectNotFoundException {

      // Define watcher and register //
      UiWatcher internetWatcher = new UiWatcher() {
          @Override
          public boolean checkForCondition() {
              UiObject noConnObj = new UiObject(new UiSelector().text("No connection"));
              if(noConnObj.exists()) {
                  UiObject retryButton = new UiObject(new UiSelector().className("android.widget.Button").text("Retry"));
                  try {
                      retryButton.click();
                      try { Thread.sleep(3000L); } catch(Exception e) {}
                      getUiDevice().pressHome();
                  } catch (UiObjectNotFoundException e) {
                      e.printStackTrace();
                  }
              }
              return false;
          }
      };
      getUiDevice().registerWatcher(NOINTERNET_STRING, internetWatcher);
      getUiDevice().runWatchers();

      // app test code //
      getUiDevice().pressHome();
      UiObject allAppsButton = new UiObject(new   UiSelector().description("Apps"));
      allAppsButton.clickAndWaitForNewWindow();
      UiObject appsTab = new UiObject(new UiSelector().description("Shop"));
      appsTab.clickAndWaitForNewWindow();

  }
}

1 个答案:

答案 0 :(得分:2)

好的,现在我明白了UiWatcher是如何工作的...... 注意:仅当某些API处于重试模式时,UiWatcher才会调用。这意味着当某些API调用无法从UI中找到元素时,UI库将自动调用您注册的观察者。

因此,如上例所示,当互联网连接关闭时打开Goog​​le Play ..现在我希望观察者活着并检查上述情况并点击重试并返回主页。只需在代码末尾添加这两行..这将处于重试模式,然后你可以看到已注册的观察者开始工作。

// below line will be in retry mode and Watcher will be invoke automatically //
        UiObject contact = new UiObject(new UiSelector().text("Contacts"));
        contact.click();