androidx.test.uiautomator.UiDevice Java Examples

The following examples show how to use androidx.test.uiautomator.UiDevice. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExecutionServer.java    From android-uiconductor with Apache License 2.0 6 votes vote down vote up
/**
 * get XML UI hierarchy.
 *
 * <p>Sample: { "width":1440, "height":2621, "xml_count": 4, "value": { "xml0": "...", "xml1":
 * "...", ... } }
 *
 * @return XML UI hierarchy JSON String.
 */
public String getDumpStrHandler(String queryParamStr) throws JSONException {
  List<String> xmls = null;
  // Get UiDevice before dumpWindowHierarchy, otherwise getWindows will return empty for the first
  // request.
  UiDevice mDevice = UiDevice.getInstance(getInstrumentation());
  xmls =
      AccessibilityNodeInfoDumper.dumpWindowHierarchy(
          queryParamStr != null && queryParamStr.toLowerCase().contains("withclassname"));
  JSONObject jsonRootObj = new JSONObject();
  JSONObject valueObj = new JSONObject();
  for (int i = 0; i < xmls.size(); i++) {
    valueObj.put(XML_KEYWORD + i, xmls.get(i));
  }
  Point devicePhysicalSize = AccessibilityNodeInfoDumper.getDevicePhysicalSize();
  jsonRootObj.put(WIDTH_KEYWORD, devicePhysicalSize.x);
  jsonRootObj.put(HEIGHT_KEYWORD, devicePhysicalSize.y);
  jsonRootObj.put(XML_COUNT_KEYWORD, xmls.size());
  jsonRootObj.put(VALUE_KEYWORD, valueObj);
  return jsonRootObj.toString();
}
 
Example #2
Source File: AccessibilityNodeInfoDumper.java    From android-uiconductor with Apache License 2.0 6 votes vote down vote up
public static Point getDevicePhysicalSize() {
  int width;
  int height;
  try {
    UiDevice mDevice = UiDevice.getInstance(getInstrumentation());
    height = mDevice.getDisplayHeight();
    width = mDevice.getDisplayWidth();
    return new Point(width, height);
  } catch (NullPointerException e) {
    Log.e(TAG, "Failed get display size, using getRealMetrics instead. " + e.getMessage());
  }
  WindowManager windowManager = (WindowManager) getInstrumentation().getContext()
      .getSystemService(Service.WINDOW_SERVICE);
  Display display =  windowManager.getDefaultDisplay();
  DisplayMetrics metrics = new DisplayMetrics();
  display.getRealMetrics(metrics);
  height = metrics.heightPixels;
  width = metrics.widthPixels;
  return new Point(width, height);

}
 
Example #3
Source File: ChangeTextBehaviorTest.java    From testing-samples with Apache License 2.0 6 votes vote down vote up
@Before
public void startMainActivityFromHomeScreen() {
    // Initialize UiDevice instance
    mDevice = UiDevice.getInstance(getInstrumentation());

    // Start from the home screen
    mDevice.pressHome();

    // Wait for launcher
    final String launcherPackage = getLauncherPackageName();
    assertThat(launcherPackage, notNullValue());
    mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT);

    // Launch the blueprint app
    Context context = getApplicationContext();
    final Intent intent = context.getPackageManager()
            .getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);    // Clear out any previous instances
    context.startActivity(intent);

    // Wait for the app to appear
    mDevice.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}
 
Example #4
Source File: NotificationListenerTests.java    From appium-uiautomator2-server with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    toastText =  new ArrayList<>();
    toastText.add("toast text");

    originalAccessibilityEventListener = mock(OnAccessibilityEventListener.class);
    PowerMockito.mockStatic(InstrumentationRegistry.class);
    when(InstrumentationRegistry.getInstrumentation()).thenReturn(null);

    PowerMockito.mockStatic(UiDevice.class);
    when(UiDevice.getInstance(null)).thenReturn(mock(UiDevice.class));
    when(UiDevice.getInstance()).thenReturn(mock(UiDevice.class));

    PowerMockito.mockStatic(UiAutomatorBridge.class);
    when(UiAutomatorBridge.getInstance()).thenReturn(mock(UiAutomatorBridge.class));

    PowerMockito.mockStatic(UiAutomation.class);
    uiAutomation = mock(UiAutomation.class);
    when(UiAutomation.getInstance()).thenReturn(uiAutomation);
    when(uiAutomation.getOnAccessibilityEventListener())
            .thenReturn(originalAccessibilityEventListener);

    notificationListener = spy(new NotificationListener());
}
 
Example #5
Source File: EnableNotificationListenerTests.java    From appium-uiautomator2-server with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    PowerMockito.mockStatic(InstrumentationRegistry.class);
    when(InstrumentationRegistry.getInstrumentation()).thenReturn(null);

    PowerMockito.mockStatic(UiDevice.class);
    when(UiDevice.getInstance(null)).thenReturn(mock(UiDevice.class));

    PowerMockito.mockStatic(UiAutomatorBridge.class);
    when(UiAutomatorBridge.getInstance()).thenReturn(mock(UiAutomatorBridge.class));

    PowerMockito.mockStatic(UiAutomation.class);
    when(UiAutomation.getInstance()).thenReturn(mock(UiAutomation.class));

    PowerMockito.mockStatic(NotificationListener.class);
    notificationListener = mock(NotificationListener.class);
    when(NotificationListener.getInstance()).thenReturn(notificationListener);

    enableNotificationListener = new EnableNotificationListener();

    doNothing().when(notificationListener).stop();
    doNothing().when(notificationListener).start();
}
 
Example #6
Source File: InstrumentedTest.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
private void press_recent() {
  try {
    UiDevice.getInstance(getInstrumentation()).pressRecentApps();
  } catch (RemoteException e) {
    e.printStackTrace();
  }
  sleep();
}
 
Example #7
Source File: AccessibilityNodeInfoHelpers.java    From appium-uiautomator2-server with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the node's bounds clipped to the size of the display, limited by the MAX_DEPTH
 *
 * @return null if node is null, else a Rect containing visible bounds
 */
@SuppressLint("CheckResult")
private static Rect getVisibleBounds(@Nullable AccessibilityNodeInfo node, int depth) {
    if (node == null) {
        return null;
    }

    // Get the object bounds in screen coordinates
    Rect ret = new Rect();
    node.getBoundsInScreen(ret);
    UiDevice uiDevice = getUiDevice();

    // Trim any portion of the bounds that are not on the screen
    Rect screen = new Rect(0, 0, uiDevice.getDisplayWidth(), uiDevice.getDisplayHeight());
    ret.intersect(screen);

    // Find the visible bounds of our first scrollable ancestor 
    for (AccessibilityNodeInfo ancestor = node.getParent(); ancestor != null && ++depth < MAX_DEPTH; ancestor = ancestor.getParent()) {
        // If this ancestor is scrollable
        if (ancestor.isScrollable()) {
            // Trim any portion of the bounds that are hidden by the non-visible portion of our
            // ancestor
            Rect ancestorRect = getVisibleBounds(ancestor, depth);
            ret.intersect(ancestorRect);
            break;
        }
    }

    return ret;
}
 
Example #8
Source File: CustomUiDevice.java    From appium-uiautomator2-server with Apache License 2.0 5 votes vote down vote up
/**
 * UiDevice in android open source project will Support multi-window searches for API level 21,
 * which has not been implemented in UiAutomatorViewer capture layout hierarchy, to be in sync
 * with UiAutomatorViewer customizing getWindowRoots() method to skip the multi-window search
 * based user passed property
 */
private CustomUiDevice() {
    try {
        this.mInstrumentation = (Instrumentation) getField(UiDevice.class, FIELD_M_INSTRUMENTATION, Device.getUiDevice());
        this.API_LEVEL_ACTUAL = getField(UiDevice.class, FIELD_API_LEVEL_ACTUAL, Device.getUiDevice());
        this.ByMatcherClass = ReflectionUtils.getClass("androidx.test.uiautomator.ByMatcher");
        this.METHOD_FIND_MATCH = method(ByMatcherClass, "findMatch", UiDevice.class, BySelector.class, AccessibilityNodeInfo[].class);
        this.METHOD_FIND_MATCHES = method(ByMatcherClass, "findMatches", UiDevice.class, BySelector.class, AccessibilityNodeInfo[].class);
        this.uiObject2Constructor = UiObject2.class.getDeclaredConstructors()[0];
        this.uiObject2Constructor.setAccessible(true);
    } catch (Exception e) {
        Logger.error("Cannot create CustomUiDevice instance", e);
        throw e;
    }
}
 
Example #9
Source File: TestUtils.java    From appium-uiautomator2-server with Apache License 2.0 5 votes vote down vote up
public static void grantPermission(final Context context, final String permission) throws
        IOException {
    Logger.info(String.format("Granting permission '%s' to %s", permission, context
            .getPackageName()));
    UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()).executeShellCommand(
            String.format(PM_GRANT_COMMAND, context.getPackageName(), permission));
}
 
Example #10
Source File: ScreenshotTest.java    From focus-android with Mozilla Public License 2.0 5 votes vote down vote up
@Before
public void setUpScreenshots() {
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    targetContext = instrumentation.getTargetContext();
    device = UiDevice.getInstance(instrumentation);

    // Use this to switch between default strategy and HostScreencap strategy
    Screengrab.setDefaultScreenshotStrategy(new UiAutomatorScreenshotStrategy());
    //Screengrab.setDefaultScreenshotStrategy(new HostScreencapScreenshotStrategy(device));

    device.waitForIdle();
}
 
Example #11
Source File: DeviceCommandsTest.java    From appium-uiautomator2-server with Apache License 2.0 5 votes vote down vote up
/**
 * Performs scrolling through a horizontal list to an element specified by its text.
 *
 * @throws JSONException
 */
@Test
public void scrollHorizontalListTest() throws JSONException {
    startActivity(".view.Tabs5"); // Page with horizontally-scrollable tabs
    waitForElement(By.id("android:id/tabs"));

    // On devices with Android API Level 23 and earlier, the tab labels are displayed
    // in all-caps, whereas their actual text is rather like 'Tab 13', 'Tab 26', etc.
    // The arguments of methods findElement() and scrollToText() are case-sensitive,
    // therefore we need to use different sets of inputs for different target devices.
    int apiLevel = (int) getField(UiDevice.class, "API_LEVEL_ACTUAL", getUiDevice());

    String[] items = apiLevel < 24
        ? new String[] { "Tab 13", "Tab 26", "Tab 5" }  // up to Android 6.0 Marshmallow
        : new String[] { "TAB 13", "TAB 26", "TAB 5" }; // Android 7.0 Nougat and later

    for (String item : items) {
        assertFalse(String.format(
            "Item '%s' should not be found in the horizontal list.", item),
            findElement(By.text(item)).isSuccessful());

        assertTrue(String.format(
            "Scroll-to-text should have succeeded for item '%s'.", item),
            scrollToText(item).isSuccessful());

        assertTrue(String.format(
            "Item '%s' should now be found in the horizontal list.", item),
            findElement(By.text(item)).isSuccessful());
    }
}
 
Example #12
Source File: AutomatorAssertion.java    From device-automator with MIT License 5 votes vote down vote up
/**
 * Asserts that the foreground app is the package specified.
 *
 * @param packageName The package to check for.
 * @return
 */
public static AutomatorAssertion foregroundAppIs(final String packageName) {
    return new AutomatorAssertion() {
        @Override
        public void wrappedCheck(UiObject object) throws UiObjectNotFoundException {
            assertTrue(UiDevice.getInstance(getInstrumentation()).hasObject(By.pkg(packageName)));
        }
    };
}
 
Example #13
Source File: ScreenshotTest.java    From firefox-echo-show with Mozilla Public License 2.0 5 votes vote down vote up
@Before
public void setUpScreenshots() {
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    targetContext = instrumentation.getTargetContext();
    device = UiDevice.getInstance(instrumentation);

    // Use this to switch between default strategy and HostScreencap strategy
    Screengrab.setDefaultScreenshotStrategy(new UiAutomatorScreenshotStrategy());
    //Screengrab.setDefaultScreenshotStrategy(new HostScreencapScreenshotStrategy(device));

    device.waitForIdle();
}
 
Example #14
Source File: UiObjectMatcherTest.java    From device-automator with MIT License 5 votes vote down vote up
@Test
public void getUiObject() {
    UiObject uiObject = mock(UiObject.class);
    UiDevice device = mock(UiDevice.class);
    when(device.findObject(any(UiSelector.class))).thenReturn(uiObject);

    UiObjectMatcher matcher = UiObjectMatcher.withClass(TextView.class);
    UiObject object = matcher.getUiObject(device);

    verify(device).findObject(matcher.getUiSelector());
    assertEquals(uiObject, object);
}
 
Example #15
Source File: ExampleInstrumentedTest.java    From za-Farmer with MIT License 5 votes vote down vote up
@Before
public void setUp() throws RemoteException {
    mUIDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());  //获得device对象
    mContext = InstrumentationRegistry.getContext();
    KeyguardManager km = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
    KeyguardManager.KeyguardLock kl = km.newKeyguardLock("farmer");
    //解锁
    kl.disableKeyguard();
    if (!mUIDevice.isScreenOn()) {
        mUIDevice.wakeUp();
    }

}
 
Example #16
Source File: UiObjectMatcher.java    From device-automator with MIT License 4 votes vote down vote up
public UiObject getUiObject(UiDevice device) {
    return device.findObject(getUiSelector());
}
 
Example #17
Source File: ExampleTest.java    From MultiSlider with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
}
 
Example #18
Source File: DeviceAutomator.java    From device-automator with MIT License 4 votes vote down vote up
public DeviceAutomator(UiDevice device, UiObjectMatcher matcher) {
    mDevice = device;
    mMatcher = matcher;
}
 
Example #19
Source File: UiScrollableParserTests.java    From appium-uiautomator2-server with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    PowerMockito.mockStatic(UiDevice.class);
    when(UiDevice.getInstance()).thenReturn(uiDevice);
    isUiObjectExist = false;
}
 
Example #20
Source File: DeviceAutomatorTest.java    From device-automator with MIT License 4 votes vote down vote up
@Before
public void setup() {
    mUiDevice = mock(UiDevice.class);
}
 
Example #21
Source File: UiAutomatorBridge.java    From appium-uiautomator2-server with Apache License 2.0 4 votes vote down vote up
public Display getDefaultDisplay() throws UiAutomator2Exception {
    return (Display) invoke(method(UiDevice.class, "getDefaultDisplay"), Device.getUiDevice());
}
 
Example #22
Source File: UiAutomatorBridge.java    From appium-uiautomator2-server with Apache License 2.0 4 votes vote down vote up
public UiAutomation getUiAutomation() {
    return (UiAutomation) invoke(method(UiDevice.class, "getUiAutomation"), Device.getUiDevice());
}
 
Example #23
Source File: UiAutomatorBridge.java    From appium-uiautomator2-server with Apache License 2.0 4 votes vote down vote up
public AccessibilityNodeInfo getAccessibilityRootNode() throws UiAutomator2Exception {
    Object queryController = invoke(method(UiDevice.class, "getQueryController"), Device.getUiDevice());
    return (AccessibilityNodeInfo) invoke(method(queryController.getClass(), "getRootNode"), queryController);
}
 
Example #24
Source File: UiAutomatorBridge.java    From appium-uiautomator2-server with Apache License 2.0 4 votes vote down vote up
public InteractionController getInteractionController() throws UiAutomator2Exception {
    return new InteractionController(invoke(method(UiDevice.class, "getInteractionController"),
            Device.getUiDevice()));
}
 
Example #25
Source File: BaseStep.java    From za-Farmer with MIT License 4 votes vote down vote up
public static final UiDevice getUiDevice() {
    return UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
}
 
Example #26
Source File: InstrumentedTest.java    From quickstart-android with Apache License 2.0 4 votes vote down vote up
private void press_back() {
  UiDevice.getInstance(getInstrumentation()).pressBack();
  sleep();

}
 
Example #27
Source File: ComplexUiActionHandler.java    From android-uiconductor with Apache License 2.0 4 votes vote down vote up
public static void zoom(Point startPoint1, Point startPoint2, Point endPoint1, Point endPoint2) {
  UiDevice uiDevice = UiDevice.getInstance(getInstrumentation());
  UiObject uiObject = uiDevice.findObject(new UiSelector());
  uiObject.performTwoPointerGesture(startPoint1, startPoint2, endPoint1, endPoint2, ZOOM_STEPS);
}
 
Example #28
Source File: AndroidTestsUtility.java    From line-sdk-android with Apache License 2.0 4 votes vote down vote up
public static boolean checkTextExists(String text) {
    UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    UiObject result = uiDevice.findObject(new UiSelector().text(text));
    return result.exists();
}
 
Example #29
Source File: AndroidTestsUtility.java    From line-sdk-android with Apache License 2.0 4 votes vote down vote up
public static boolean checkElementExists(String className) {
    UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    uiDevice.wait(Until.hasObject(By.clazz(className)), AndroidTestsConfig.TIMEOUT);
    UiObject2 element = uiDevice.findObject(By.clazz(className));
    return element.isEnabled() && element.isClickable() && element.isFocusable();
}
 
Example #30
Source File: AndroidTestsUtility.java    From line-sdk-android with Apache License 2.0 4 votes vote down vote up
public static boolean checkElementExists(int resourceId) {
    UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    Context context = ApplicationProvider.getApplicationContext();
    return uiDevice.wait(Until.hasObject(By.res(toResourceName(context, resourceId))), AndroidTestsConfig.TIMEOUT);
}