Java Code Examples for android.support.test.uiautomator.UiSelector

The following examples show how to use android.support.test.uiautomator.UiSelector. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Expert-Android-Programming   Source File: UIAnimatorTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testChangeText_sameActivity() {


    UiObject skipButton = mDevice.findObject(new UiSelector()
            .text("SKIP").className("android.widget.TextView"));

    // Simulate a user-click on the OK button, if found.
    try {
        if (skipButton.exists() && skipButton.isEnabled()) {
                skipButton.click();
        }
    } catch (UiObjectNotFoundException e) {
        e.printStackTrace();
    }
}
 
Example 2
public void allowPermissionsIfNeeded() {
    try {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            sleep(PERMISSIONS_DIALOG_DELAY);
            UiDevice device = UiDevice.getInstance(getInstrumentation());
            UiSelector selector = new UiSelector()
                    .clickable(true)
                    .checkable(false)
                    .index(GRANT_BUTTON_INDEX);
            UiObject allowPermissions = device.findObject(selector);

            if (allowPermissions.exists()) {
                allowPermissions.click();
            }
        }

    } catch (UiObjectNotFoundException e) {
        System.out.println("There is no permissions dialog to interact with");
    }
}
 
Example 3
public void allowPermissionsIfNeeded() {
    try {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            sleep(PERMISSIONS_DIALOG_DELAY);
            UiDevice device = UiDevice.getInstance(getInstrumentation());
            UiObject allowPermissions = device.findObject(new UiSelector()
                    .clickable(true)
                    .checkable(false)
                    .index(GRANT_BUTTON_INDEX));

            if (allowPermissions.exists()) {
                allowPermissions.click();
            }
        }

    } catch (UiObjectNotFoundException e) {
        System.out.println("There is no permissions dialog to interact with");
    }
}
 
Example 4
Source Project: android-testing-guide   Source File: MainActivityTest.java    License: MIT License 6 votes vote down vote up
@Ignore
@Test
public void testUiAutomatorAPI() throws UiObjectNotFoundException, InterruptedException {
    UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

    UiSelector editTextSelector = new UiSelector().className("android.widget.EditText").text("this is a test").focusable(true);
    UiObject editTextWidget = device.findObject(editTextSelector);
    editTextWidget.setText("this is new text");

    Thread.sleep(2000);

    UiSelector buttonSelector = new UiSelector().className("android.widget.Button").text("CLICK ME").clickable(true);
    UiObject buttonWidget = device.findObject(buttonSelector);
    buttonWidget.click();

    Thread.sleep(2000);
}
 
Example 5
Source Project: SweetBlue   Source File: UIUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static boolean viewExistsContains(UiDevice device, String... textToMatch) throws UiObjectNotFoundException
{
    if (textToMatch == null || textToMatch.length < 1)
    {
        return false;
    }
    UiObject view;
    boolean contains = false;
    for (int i = 0; i < textToMatch.length; i++)
    {
        view = device.findObject(new UiSelector().textContains(textToMatch[i]));
        contains = view.exists();
        if (contains) return true;
    }
    return false;
}
 
Example 6
Source Project: SmoothClicker   Source File: ItStandaloneModeDialog.java    License: MIT License 6 votes vote down vote up
/**
 * Opens the standalone mode dialog
 */
private void openStandaloneModeDialog(){
    try {
        // Display the pop-up
        UiObject menu = mDevice.findObject(
                new UiSelector().className("android.widget.ImageView")
                        //.description("Plus d'options") // FIXME Raw french string
                        .description("Autres options") // WARNING FIXME French string used, use instead system R values
        );
        menu.click();
        UiObject menuItem = mDevice.findObject(
                new UiSelector().className("android.widget.TextView").text(InstrumentationRegistry.getTargetContext().getString(R.string.action_standalone))
        );
        menuItem.click();
    } catch ( UiObjectNotFoundException uinfe ){
        uinfe.printStackTrace();
        fail(uinfe.getMessage());
    }
}
 
Example 7
Source Project: SmoothClicker   Source File: ItNotificationsManager.java    License: MIT License 6 votes vote down vote up
/**
 * Inner method to get a dedicated notification and test it
 * @param textContent - The text to use to get the notification
 */
private void testIfNotificationExists( String textContent ) {

    UiObject n = null;

    if ( Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT_WATCH ){
        n = mDevice.findObject(
                new UiSelector()
                    .resourceId("android:id/text")
                    .className("android.widget.TextView")
                    .packageName("pylapp.smoothclicker.android")
                    .textContains(textContent));
    } else {
        n = mDevice.findObject(
                new UiSelector()
                        .resourceId("android:id/text")
                        .className("android.widget.TextView")
                        .packageName("com.android.systemui")
                        .textContains(textContent));
    }

    mDevice.openNotification();
    n.waitForExists(2000);
    assertTrue(n.exists());

}
 
Example 8
Source Project: SmoothClicker   Source File: ItServiceClicker.java    License: MIT License 6 votes vote down vote up
/**
 * Inner method to get a dedicated notification and test it
 * @param textContent - The text to use to get the notification
 */
private void testNotification( String textContent ){

    UiObject n = null;

    if ( Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT_WATCH ){
        n = mDevice.findObject(
                new UiSelector()
                        .resourceId("android:id/text")
                        .className("android.widget.TextView")
                        .packageName("pylapp.smoothclicker.android")
                        .textContains(textContent));
    } else {
        n = mDevice.findObject(
                new UiSelector()
                        .resourceId("android:id/text")
                        .className("android.widget.TextView")
                        .packageName("com.android.systemui")
                        .textContains(textContent));
    }

    mDevice.openNotification();
    n.waitForExists(60000);
    assertTrue(n.exists());

}
 
Example 9
Source Project: AppCrawler   Source File: UiWatchers.java    License: Apache License 2.0 6 votes vote down vote up
public boolean handleAnr2() {
    UiObject window = sDevice.findObject(new UiSelector().packageName("android")
            .textContains("isn't responding."));
    if (!window.exists()) {
        window = sDevice.findObject(new UiSelector().packageName("android")
                .textContains("沒有回應"));
    }
    if (window.exists()) {
        String errorText = null;
        try {
            errorText = window.getText();
        } catch (UiObjectNotFoundException e) {
            Log.e(TAG, "dialog gone?", e);
        }
        onAnrDetected(errorText);
        postHandler();
        return true; // triggered
    }
    return false; // no trigger
}
 
Example 10
Source Project: AppCrawler   Source File: UiWatchers.java    License: Apache License 2.0 6 votes vote down vote up
public boolean handleCrash() {
    UiObject window = sDevice.findObject(new UiSelector()
            .className("com.android.server.am.AppErrorDialog"));
    if (window.exists()) {
        String errorText = null;
        try {
            errorText = window.getText();
        } catch (UiObjectNotFoundException e) {
            Log.e(TAG, "dialog gone?", e);
        }
        onCrashDetected(errorText);
        postHandler();
        return true; // triggered
    }
    return false; // no trigger
}
 
Example 11
Source Project: AppCrawler   Source File: UiWatchers.java    License: Apache License 2.0 6 votes vote down vote up
public boolean handleCrash2() {
    UiObject window = sDevice.findObject(new UiSelector().packageName("android")
            .textContains("has stopped"));
    if (!window.exists()) {
        window = sDevice.findObject(new UiSelector().packageName("android")
                .textContains("已停止運作"));
    }
    if (window.exists()) {
        String errorText = null;
        try {
            errorText = window.getText();
        } catch (UiObjectNotFoundException e) {
            Log.e(TAG, "dialog gone?", e);
        }
        UiHelper.takeScreenshots("[CRASH]");
        onCrashDetected(errorText);
        postHandler();
        return true; // triggered
    }
    return false; // no trigger
}
 
Example 12
Source Project: AppCrawler   Source File: UiHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static void inputRandomTextToEditText() {
    UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    UiObject edit = null;
    int i = 0;
    do {
        edit = null;
        edit = device.findObject(new UiSelector().className("android.widget.EditText").instance(i++));
        if (edit != null && edit.exists()) {
            try {
                Random rand = new Random();
                String text = Config.RANDOM_TEXT[rand.nextInt(Config.RANDOM_TEXT.length - 1)];
                edit.setText(text);
            } catch (UiObjectNotFoundException e) {
                // Don't worry
            }
        }
    } while (edit != null && edit.exists());
}
 
Example 13
Source Project: android-uiautomator-server   Source File: AutomatorServiceImpl.java    License: MIT License 6 votes vote down vote up
/**
 * Register a ClickUiObjectWatcher
 *
 * @param name       Watcher name
 * @param conditions If all UiObject in the conditions match, the watcher should be triggered.
 * @param target     The target UiObject should be clicked if all conditions match.
 */
@Override
public void registerClickUiObjectWatcher(String name, Selector[] conditions, Selector target) {
    synchronized (watchers) {
        if (watchers.contains(name)) {
            device.removeWatcher(name);
            watchers.remove(name);
        }

        UiSelector[] selectors = new UiSelector[conditions.length];
        for (int i = 0; i < conditions.length; i++) {
            selectors[i] = conditions[i].toUiSelector();
        }
        device.registerWatcher(name, new ClickUiObjectWatcher(selectors, target.toUiSelector()));
        watchers.add(name);
    }
}
 
Example 14
Source Project: android-uiautomator-server   Source File: AutomatorServiceImpl.java    License: MIT License 6 votes vote down vote up
/**
 * Register a PressKeysWatcher
 *
 * @param name       Watcher name
 * @param conditions If all UiObject in the conditions match, the watcher should be triggered.
 * @param keys       All keys will be pressed in sequence.
 */
@Override
public void registerPressKeyskWatcher(String name, Selector[] conditions, String[] keys) {
    synchronized (watchers) {
        if (watchers.contains(name)) {
            device.removeWatcher(name);
            watchers.remove(name);
        }

        UiSelector[] selectors = new UiSelector[conditions.length];
        for (int i = 0; i < conditions.length; i++) {
            selectors[i] = conditions[i].toUiSelector();
        }
        device.registerWatcher(name, new PressKeysWatcher(selectors, keys));
        watchers.add(name);
    }
}
 
Example 15
Source Project: android-uiautomator-server   Source File: AutomatorServiceImpl.java    License: MIT License 6 votes vote down vote up
/**
 * Get the count of the UiObject instances by the selector
 *
 * @param obj the selector of the ui object
 * @return the count of instances.
 */
@Override
public int count(Selector obj) {
    if ((obj.getMask() & Selector.MASK_INSTANCE) > 0) {
        if (device.findObject(obj.toUiSelector()).exists()) return 1;
        else return 0;
    } else {
        UiSelector sel = obj.toUiSelector();
        if (!device.findObject(sel).exists()) return 0;
        int low = 1;
        int high = 2;
        sel = sel.instance(high - 1);
        while (device.findObject(sel).exists()) {
            low = high;
            high = high * 2;
            sel = sel.instance(high - 1);
        }
        while (high > low + 1) {
            int mid = (low + high) / 2;
            sel = sel.instance(mid - 1);
            if (device.findObject(sel).exists()) low = mid;
            else high = mid;
        }
        return low;
    }
}
 
Example 16
private void allowPermissionsIfNeeded() {
    if (Build.VERSION.SDK_INT >= 23) {
        // Initialize UiDevice instance
        UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

        // notice that we typically receive 2-3 permission prompts, hence the loop
        while (true) {
            UiObject allowPermissions = uiDevice.findObject(new UiSelector().text("Allow"));
            if (allowPermissions.exists()) {
                try {
                    allowPermissions.click();
                } catch (UiObjectNotFoundException e) {
                    e.printStackTrace();
                    Log.e(TAG, "There is no permissions dialog to interact with ");
                }
            } else {
                break;
            }
        }
    }
}
 
Example 17
Source Project: SweetBlue   Source File: UIUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static boolean viewExistsContains(UiDevice device, String... textToMatch) throws UiObjectNotFoundException
{
    if (textToMatch == null || textToMatch.length < 1)
    {
        return false;
    }
    UiObject view;
    boolean contains = false;
    for (int i = 0; i < textToMatch.length; i++)
    {
        view = device.findObject(new UiSelector().textContains(textToMatch[i]));
        contains = view.exists();
        if (contains) return true;
    }
    return false;
}
 
Example 18
@Test
public void it_should_be_possible_to_open_add_new_item_window() throws UiObjectNotFoundException {
    mDevice.findObject(
            new UiSelector()
                    .descriptionContains("Add New Stock Button")
    ).click();

    UiObject2 result = mDevice.findObject(
            By.res(TARGET_PACKAGE, "portfolio_addnew_symbol")
    );

    assertThat(result.getText(), is("GOOG"));
}
 
Example 19
@Test
public void it_should_be_possible_to_open_add_new_item_window() throws UiObjectNotFoundException {
    mDevice.findObject(
            new UiSelector()
                    .descriptionContains("Add New Stock Button")
    ).click();

    UiObject2 result = mDevice.findObject(
            By.res(TARGET_PACKAGE, "portfolio_addnew_symbol")
    );

    assertThat(result.getText(), is("GOOG"));
}
 
Example 20
@Test
public void it_should_be_possible_to_open_add_new_item_window() throws UiObjectNotFoundException {
    mDevice.findObject(
            new UiSelector()
                    .descriptionContains("Add New Stock Button")
    ).click();

    UiObject2 result = mDevice.findObject(
            By.res(TARGET_PACKAGE, "portfolio_addnew_symbol")
    );

    assertThat(result.getText(), is("GOOG"));
}
 
Example 21
@Test
public void it_should_be_possible_to_open_add_new_item_window() throws UiObjectNotFoundException {
    mDevice.findObject(
            new UiSelector()
                    .descriptionContains("Add New Stock Button")
    ).click();

    UiObject2 result = mDevice.findObject(
            By.res(TARGET_PACKAGE, "portfolio_addnew_symbol")
    );

    assertThat(result.getText(), is("GOOG"));
}
 
Example 22
@Test
public void it_should_be_possible_to_open_add_new_item_window() throws UiObjectNotFoundException {
    mDevice.findObject(
            new UiSelector()
                    .descriptionContains("Add New Stock Button")
    ).click();

    UiObject2 result = mDevice.findObject(
            By.res(TARGET_PACKAGE, "portfolio_addnew_symbol")
    );

    assertThat(result.getText(), is("GOOG"));
}
 
Example 23
@Test
public void it_should_be_possible_to_open_add_new_item_window() throws UiObjectNotFoundException {
    mDevice.findObject(
            new UiSelector()
                    .descriptionContains("Add New Stock Button")
    ).click();

    UiObject2 result = mDevice.findObject(
            By.res(TARGET_PACKAGE, "portfolio_addnew_symbol")
    );

    assertThat(result.getText(), is("GOOG"));
}
 
Example 24
@Test
public void it_should_be_possible_to_open_add_new_item_window() throws UiObjectNotFoundException {
    mDevice.findObject(
            new UiSelector()
                    .descriptionContains("Add New Stock Button")
    ).click();

    UiObject2 result = mDevice.findObject(
            By.res(TARGET_PACKAGE, "portfolio_addnew_symbol")
    );

    assertThat(result.getText(), is("GOOG"));
}
 
Example 25
Source Project: UIAutomatorWD   Source File: UIAutomatorWD.java    License: MIT License 5 votes vote down vote up
public void skipPermission(JSONArray permissionPatterns, int scanningCount) {
    UiDevice mDevice = Elements.getGlobal().getmDevice();

    // if permission list is empty, avoid execution
    if (permissionPatterns.size() == 0) {
        return;
    }

    // regular check for permission scanning
    try {
        for (int i = 0; i < scanningCount; i++) {
            inner:
            for (int j = 0; j < permissionPatterns.size(); j++) {
                String text = permissionPatterns.getString(j);
                UiObject object = mDevice.findObject(new UiSelector().text(text));
                if (object.exists()) {
                    object.click();
                    break inner;
                }
            }

            Thread.sleep(3000);
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
        System.out.println(e.getCause().toString());
    }
}
 
Example 26
Source Project: Forage   Source File: UiAutomatorUtils.java    License: Mozilla Public License 2.0 5 votes vote down vote up
public static void allowPermissionsIfNeeded(UiDevice device) {
    if (Build.VERSION.SDK_INT >= 23) {
        UiObject allowPermissions = device.findObject(new UiSelector().text(TEXT_ALLOW));

        if (allowPermissions.exists()) {
            try {
                allowPermissions.click();
            } catch (UiObjectNotFoundException ignored) {
            }
        }
    }
}
 
Example 27
Source Project: AndroidProjects   Source File: MainEspressoTest.java    License: MIT License 5 votes vote down vote up
@Test
public void d() throws UiObjectNotFoundException {
    // Initialize UiDevice instance
    mDevice = UiDevice.getInstance(getInstrumentation());

    // Perform a short press on the HOME button
    mDevice.pressHome();

    // Bring up the default launcher by searching for
    // a UI component that matches the content-description for the launcher button
    UiObject allAppsButton = mDevice.findObject(new UiSelector().description("Apps"));

    // Perform a click on the button to bring up the launcher
    allAppsButton.clickAndWaitForNewWindow();
}
 
Example 28
Source Project: espresso-macchiato   Source File: EspPermissionDialog.java    License: MIT License 5 votes vote down vote up
protected void click(String targetId) {
    UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    UiObject button = device.findObject(new UiSelector().resourceId(targetId));

    try {
        button.waitForExists(3000);
        button.click();
    } catch (UiObjectNotFoundException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 29
Source Project: espresso-macchiato   Source File: EspSystemDialog.java    License: MIT License 5 votes vote down vote up
protected void click(String target) {
    UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    UiObject button = device.findObject(new UiSelector().text(target));

    try {
        button.click();
    } catch (UiObjectNotFoundException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 30
Source Project: SmoothClicker   Source File: ItSelectMultiPointsActivity.java    License: MIT License 5 votes vote down vote up
/**
 * Tests if the snack bar is displayed when a point has been clicked
 *
 * <i>If a point with (x,y) coordinates has been chosen, a snackbar with the following text has to be displayed "Click X = x / Y =  y"</i>
 */
@Test
public void snackBarNewPoint(){

    l(this, "@Test snackBarNewPoint");

    final int X = 500;
    final int Y = 600;
    final String S = "Click X = " + X + " / Y = " + Y;

    try {

        // Wait for the activity because Espresso is too fast
        w(5000);

        // Click on the dedicated screen to make a new point
        clickAt(X, Y);

        // Get the snack bar
        UiObject snackBar = mDevice.findObject(
                new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/snackbar_text")
        );

        w(2000);
        assertTrue(snackBar.exists());
        assertEquals( S, snackBar.getText());

    } catch ( UiObjectNotFoundException uonfe ){
        uonfe.printStackTrace();
        fail( uonfe.getMessage() );
    }

}