2

导入 com.android.uiautomator.core.UiObject;导入 com.android.uiautomator.core.UiObjectNotFoundException;导入 com.android.uiautomator.core.UiSelector;导入 com.android.uiautomator.core.UiWatcher;导入 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();

  }
}
4

1 回答 1

3

好的,现在我了解了 UiWatcher 的工作原理…… 注意:只有当某些 API 处于重试模式时,UiWatcher 才会调用。这意味着当某些 API 调用无法从 UI 中找到元素时,UI 库将自动调用您注册的观察者。

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

// below line will be in retry mode and Watcher will be invoke automatically //
        UiObject contact = new UiObject(new UiSelector().text("Contacts"));
        contact.click();
于 2013-07-24T04:25:39.557 回答