类android.support.test.uiautomator.UiDevice源码实例Demo

下面列出了怎么用android.support.test.uiautomator.UiDevice的API类实例代码及写法,或者点击链接到github查看源代码。

@Before
public void startMainActivityFromHomeScreen() {
    mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    mDevice.pressHome();

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

    Context context = InstrumentationRegistry.getContext();
    final Intent intent = context.getPackageManager().getLaunchIntentForPackage(TARGET_PACKAGE);

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);

    mDevice.wait(Until.hasObject(By.pkg(TARGET_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}
 
@Before
public void startMainActivityFromHomeScreen() {
    mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    mDevice.pressHome();

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

    Context context = InstrumentationRegistry.getContext();
    final Intent intent = context.getPackageManager().getLaunchIntentForPackage(TARGET_PACKAGE);

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);

    mDevice.wait(Until.hasObject(By.pkg(TARGET_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}
 
@Before
public void startMainActivityFromHomeScreen() {
    mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    mDevice.pressHome();

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

    Context context = InstrumentationRegistry.getContext();
    final Intent intent = context.getPackageManager().getLaunchIntentForPackage(TARGET_PACKAGE);

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);

    mDevice.wait(Until.hasObject(By.pkg(TARGET_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}
 
@Before
public void startMainActivityFromHomeScreen() {
    mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    mDevice.pressHome();

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

    Context context = InstrumentationRegistry.getContext();
    final Intent intent = context.getPackageManager().getLaunchIntentForPackage(TARGET_PACKAGE);

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);

    mDevice.wait(Until.hasObject(By.pkg(TARGET_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}
 
@Before
public void startMainActivityFromHomeScreen() {
    mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    mDevice.pressHome();

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

    Context context = InstrumentationRegistry.getContext();
    final Intent intent = context.getPackageManager().getLaunchIntentForPackage(TARGET_PACKAGE);

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);

    mDevice.wait(Until.hasObject(By.pkg(TARGET_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}
 
@Before
public void startMainActivityFromHomeScreen() {
    mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    mDevice.pressHome();

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

    Context context = InstrumentationRegistry.getContext();
    final Intent intent = context.getPackageManager().getLaunchIntentForPackage(TARGET_PACKAGE);

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);

    mDevice.wait(Until.hasObject(By.pkg(TARGET_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}
 
@Before
public void startMainActivityFromHomeScreen() {
    // Initialize UiDevice instance
    mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

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

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

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

    // Wait for the app to appear
    mDevice.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)),
            LAUNCH_TIMEOUT);
}
 
源代码8 项目: UIAutomatorWD   文件: AlertController.java
private static UiObject2 getAlertButton(String alertType) throws Exception {
    UiDevice mDevice = Elements.getGlobal().getmDevice();
    int buttonIndex;
    if (alertType.equals("accept")) {
        buttonIndex = 1;
    } else if (alertType.equals("dismiss")) {
        buttonIndex = 0;
    } else {
        throw new Exception("alertType can only be 'accept' or 'dismiss'");
    }

    List<UiObject2> alertButtons = mDevice.findObjects(By.clazz("android.widget.Button").clickable(true).checkable(false));
    if (alertButtons.size() == 0) {
        return null;
    }
    UiObject2 alertButton = alertButtons.get(buttonIndex);

    return alertButton;
}
 
源代码9 项目: UIAutomatorWD   文件: KeysController.java
@Override
public NanoHTTPD.Response get(RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) {
    String sessionId = urlParams.get("sessionId");
    Map<String, String> body = new HashMap<String, String>();
    UiDevice mDevice = Elements.getGlobal().getmDevice();
    JSONObject result = null;
    try {
        session.parseBody(body);
        String postData = body.get("postData");
        JSONObject jsonObj = JSON.parseObject(postData);
        JSONArray keycodes = (JSONArray)jsonObj.get("value");
        for (Iterator iterator = keycodes.iterator(); iterator.hasNext();) {
            int keycode = (int) iterator.next();
            mDevice.pressKeyCode(keycode);
        }
        return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(result, sessionId).toString());
    } catch (Exception e) {
        return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.UnknownError, sessionId).toString());
    }
}
 
源代码10 项目: mobile-android-samples   文件: PermissionGranter.java
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");
    }
}
 
源代码11 项目: mobile-android-samples   文件: PermissionGranter.java
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");
    }
}
 
源代码12 项目: android-testing-guide   文件: MainActivityTest.java
@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);
}
 
源代码13 项目: AppCrawler   文件: UiHelper.java
public static boolean handleCommonDialog() {
    UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    UiObject button = null;
    for (String keyword : Config.COMMON_BUTTONS) {
        button = device.findObject(new UiSelector().text(keyword).enabled(true));
        if (button != null && button.exists()) {
            break;
        }
    }
    try {
        // sometimes it takes a while for the OK button to become enabled
        if (button != null && button.exists()) {
            button.waitForExists(5000);
            button.click();
            Log.i("AppCrawlerAction", "{Click} " + button.getText() + " Button succeeded");
            return true; // triggered
        }
    } catch (UiObjectNotFoundException e) {
        Log.w(TAG, "UiObject disappear");
    }
    return false; // no trigger
}
 
源代码14 项目: AppCrawler   文件: UiHelper.java
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());
}
 
源代码15 项目: android-uiautomator-server   文件: DeviceInfo.java
private DeviceInfo() {
this._sdkInt = android.os.Build.VERSION.SDK_INT;

UiDevice ud = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
this._currentPackageName = ud.getCurrentPackageName();
this._displayWidth = ud.getDisplayWidth();
this._displayHeight = ud.getDisplayHeight();
this._displayRotation = ud.getDisplayRotation();
this._productName = ud.getProductName();
this._naturalOrientation = ud.isNaturalOrientation();
this._displaySizeDpX = ud.getDisplaySizeDp().x;
this._displaySizeDpY = ud.getDisplaySizeDp().y;
      try {
          this._screenOn = ud.isScreenOn();
      } catch (RemoteException e) {
          e.printStackTrace();
          Log.e(e.getMessage());
      }
  }
 
源代码16 项目: espresso-samples   文件: PermissionsTest.java
@Before
public void startMainActivityFromHomeScreen() {
    // Initialize UiDevice instance
    device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

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

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

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

    // Wait for the app to appear
    device.wait(Until.hasObject(By.pkg(APP_PACKAGE_NAME).depth(0)), LAUNCH_TIMEOUT);
}
 
/**
 * When using UiAutomator you can interact with ui elements outside of your own process.
 * You can start your application by pressing the home button of the device and launch the
 * target app through the android launcher.
 *
 * <p>
 * If you only want to launch and test a single {@link Activity} you can use {@link
 * Instrumentation} directly to only launch the target {@link Activity}
 * </p>
 */
@Before
public void startBlueprintActivityFromHomeScreen() {
    // Initialize UiDevice instance
    mDevice = UiDevice.getInstance(InstrumentationRegistry.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 = InstrumentationRegistry.getContext();
    final Intent intent = context.getPackageManager().getLaunchIntentForPackage(TARGET_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(TARGET_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}
 
源代码18 项目: SweetBlue   文件: UIUtil.java
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;
}
 
源代码19 项目: restcomm-android-sdk   文件: BasicUITests.java
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;
            }
        }
    }
}
 
源代码20 项目: SweetBlue   文件: UIUtil.java
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;
}
 
源代码21 项目: SweetBlue   文件: UIUtil.java
public static void handleBluetoothEnablerDialogs(UiDevice uiDevice, Activity activity) throws UiObjectNotFoundException
{
    if (viewExistsExact(uiDevice, "Bluetooth permission request"))
    {
        if (viewExistsExact(uiDevice, "ALLOW"))
        {
            clickButton(uiDevice, "ALLOW");
        }
        else if (viewExistsExact(uiDevice, "Yes"))
        {
            clickButton(uiDevice, "Yes");
        }
    }
    if (viewExistsExact(uiDevice, P_StringHandler.getString(activity, P_StringHandler.REQUIRES_LOCATION_PERMISSION)))
    {
        clickButton(uiDevice, P_StringHandler.getString(activity, P_StringHandler.ACCEPT));
    }
    if (viewExistsContains(uiDevice, "Allow", "access this device's location") && UIUtil.viewExistsExact(uiDevice, "ALLOW") && UIUtil.viewExistsExact(uiDevice, "DENY"))
    {
        clickButton(uiDevice, "ALLOW");
    }
}
 
源代码22 项目: UIAutomatorWD   文件: WindowController.java
@Override
public NanoHTTPD.Response get(RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) {
    String sessionId = urlParams.get("sessionId");
    try {
        UiDevice mDevice = Elements.getGlobal().getmDevice();
        Integer width = mDevice.getDisplayWidth();
        Integer height = mDevice.getDisplayHeight();
        JSONObject size = new JSONObject();
        size.put("width", width);
        size.put("height", height);
        return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(size, sessionId).toString());
    } catch(Exception e) {
        return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.UnknownError, sessionId).toString());
    }
}
 
源代码23 项目: UIAutomatorWD   文件: UIAutomatorWD.java
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());
    }
}
 
源代码24 项目: OPFIab   文件: ActivityHelperTest.java
@Before
public void setUp() throws InterruptedException {
    Thread.sleep(WAIT_TEST_MANAGER);
    instrumentation = InstrumentationRegistry.getInstrumentation();
    activity = testRule.getActivity();
    uiDevice = UiDevice.getInstance(instrumentation);
}
 
源代码25 项目: Forage   文件: UiAutomatorUtils.java
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) {
            }
        }
    }
}
 
源代码26 项目: AndroidProjects   文件: MainEspressoTest.java
@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();
}
 
源代码27 项目: espresso-macchiato   文件: EspPermissionDialog.java
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);
    }
}
 
源代码28 项目: android-testing-guide   文件: MainActivityTest.java
@Test
public void testUiDevice() throws RemoteException {
    UiDevice device = UiDevice.getInstance(
            InstrumentationRegistry.getInstrumentation());
    if (device.isScreenOn()) {
        device.setOrientationLeft();
        device.openNotification();
    }
}
 
源代码29 项目: SmoothClicker   文件: AbstractTest.java
/**
 * <i>The tests have to start from the screen home</i>
 */
@BeforeClass
public static void start(){
    l("AbstractTest","@BeforeClass start");
    UiDevice d = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    d.pressHome();
}
 
源代码30 项目: SmoothClicker   文件: AbstractTest.java
/**
 * <i>The device should be at its initial state when all tests are done</i>
 */
@AfterClass
public static void end(){
    l("AbstractTest","@AfterClass end");
    UiDevice d = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    d.pressHome();
}
 
 类所在包
 同包方法