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

The following are top voted examples for showing how to use android.support.test.uiautomator.UiDevice. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: smart-lens   File: BaseTestClass.java   View source code 9 votes vote down vote up
@Before
public void setup() {
    // Unlock the screen if it's locked
    UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    try {
        device.wakeUp();
    } catch (RemoteException e) {
        e.printStackTrace();
    }

    // Set the flags on our activity so it'll appear regardless of lock screen state
    new Handler(Looper.getMainLooper()).post(() -> {
        if (getActivity() == null) return;
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    });
}
 
Example 2
Project: FancyTrendView   File: GoogleTrendActivityUiAutomatorTest.java   View source code 7 votes vote down vote up
@Before
public void startMainActivityFromHomeScreen() throws Exception {
    // Initialize UiDevice instance
    mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    // Start from the home screen
    mDevice.pressHome();

    // Wait for launcher
    final String launcherPackage = mDevice.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(BASIC_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_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}
 
Example 3
Project: ChimpCheck   File: ExampleInstrumentedTest.java   View source code 7 votes vote down vote up
@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 = 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(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
Project: ChimpCheck   File: PermissionGranter.java   View source code 7 votes vote down vote up
public static void allowPermissionsIfNeeded(String permissionNeeded) {
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !hasNeededPermission(permissionNeeded)) {
            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 5
Project: SimpleMarkdown   File: MainActivityTests.java   View source code 7 votes vote down vote up
@Test
public void openAppTest() throws Exception {
    UiDevice mDevice = UiDevice.getInstance(getInstrumentation());
    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 load the launcher.
    allAppsButton.clickAndWaitForNewWindow();
    // Context of the app under test.
    Context appContext = InstrumentationRegistry.getTargetContext();

    assertEquals("com.wbrawner.simplemarkdown", appContext.getPackageName());
    UiScrollable appView = new UiScrollable(new UiSelector().scrollable(true));
    UiSelector simpleMarkdownSelector = new UiSelector().text("Simple Markdown");
    appView.scrollIntoView(simpleMarkdownSelector);
    mDevice.findObject(simpleMarkdownSelector).clickAndWaitForNewWindow();
}
 
Example 6
Project: Expert-Android-Programming   File: UIAnimatorTest.java   View source code 7 votes vote down vote up
@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);
}
 
Example 7
Project: AsteroidOSSync   File: UIUtil.java   View source code 7 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 8
Project: ibeacon-scanner-android   File: PermissionTestHelper.java   View source code 7 votes vote down vote up
/**
 * Allows location permission if the runtime permission dialog is shown.
 */
public static void allowLocationPermissionWhenAsked()
{
    try
    {
        if (!PermissionUtils.isLocationGranted(InstrumentationRegistry.getTargetContext()))
        {
            TestHelper.sleep(PERMISSIONS_DIALOG_DELAY);

            final UiDevice device = UiDevice.getInstance(getInstrumentation());
            final UiObject allowPermissions = device.findObject(new UiSelector()
                                                                        .clickable(true)
                                                                        .checkable(false)
                                                                        .index(GRANT_BUTTON_INDEX));
            if (allowPermissions.exists())
            {
                allowPermissions.click();
            }
        }
    }
    catch (final UiObjectNotFoundException e)
    {
        Log.e(PermissionTestHelper.class.getSimpleName(), "There is no permissions dialog to interact with.");
    }
}
 
Example 9
Project: android-testing-guide   File: MainActivityTest.java   View source code 7 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 10
Project: Demos   File: UiTest.java   View source code 6 votes vote down vote up
/**
 * 测试CollapsingToolbarLayout
 * 被测Demo下载地址:https://github.com/alidili/DesignSupportDemo
 *
 * @throws UiObjectNotFoundException
 */
public void testA() throws UiObjectNotFoundException {
    // 获取设备对象
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    UiDevice uiDevice = UiDevice.getInstance(instrumentation);
    // 获取上下文
    Context context = instrumentation.getContext();

    // 启动测试App
    Intent intent = context.getPackageManager().getLaunchIntentForPackage("com.yang.designsupportdemo");
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);

    // 打开CollapsingToolbarLayout
    String resourceId = "com.yang.designsupportdemo:id/CollapsingToolbarLayout";
    UiObject collapsingToolbarLayout = uiDevice.findObject(new UiSelector().resourceId(resourceId));
    collapsingToolbarLayout.click();

    for (int i = 0; i < 5; i++) {
        // 向上移动
        uiDevice.swipe(uiDevice.getDisplayHeight() / 2, uiDevice.getDisplayHeight(),
                uiDevice.getDisplayHeight() / 2, uiDevice.getDisplayHeight() / 2, 10);

        // 向下移动
        uiDevice.swipe(uiDevice.getDisplayHeight() / 2, uiDevice.getDisplayHeight() / 2,
                uiDevice.getDisplayHeight() / 2, uiDevice.getDisplayHeight(), 10);
    }

    // 点击应用返回按钮
    UiObject back = uiDevice.findObject(new UiSelector().description("Navigate up"));
    back.click();

    // 点击设备返回按钮
    uiDevice.pressBack();
}
 
Example 11
Project: Demos   File: UiTest.java   View source code 6 votes vote down vote up
/**
 * 滑动界面,打开About phone选项
 * 测试环境为标准Android 7.1.1版本,不同设备控件查找方式会有不同
 *
 * @throws UiObjectNotFoundException
 */
public void testB() throws UiObjectNotFoundException {
    // 获取设备对象
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    UiDevice uiDevice = UiDevice.getInstance(instrumentation);
    // 获取上下文
    Context context = instrumentation.getContext();

    // 点击Settings按钮
    UiObject uiObject = uiDevice.findObject(new UiSelector().description("Settings"));
    uiObject.click();

    // 滑动列表到最后,点击About phone选项
    UiScrollable settings = new UiScrollable(new UiSelector().className("android.support.v7.widget.RecyclerView"));
    UiObject about = settings.getChildByText(new UiSelector().className("android.widget.LinearLayout"), "About phone");
    about.click();

    // 点击设备返回按钮
    uiDevice.pressBack();
    uiDevice.pressBack();
}
 
Example 12
Project: UIAutomatorWD   File: WindowController.java   View source code 6 votes vote down vote up
@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());
    }
}
 
Example 13
Project: UIAutomatorWD   File: AlertController.java   View source code 6 votes vote down vote up
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;
}
 
Example 14
Project: UIAutomatorWD   File: KeysController.java   View source code 6 votes vote down vote up
@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());
    }
}
 
Example 15
Project: firefox-tv   File: ScreenshotTest.java   View source code 6 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 16
Project: DeviceAnimationTestRule   File: DeviceAnimationTestRule.java   View source code 6 votes vote down vote up
private void disableAnimations() throws Exception {
  Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();

  UiDevice
      .getInstance(InstrumentationRegistry.getInstrumentation())
      .executeShellCommand(
          "pm grant "
              + InstrumentationRegistry.getInstrumentation().getTargetContext().getPackageName()
              + " "
              + ANIMATION_PERMISSION
      );

  Context context = instrumentation.getContext();

  int permStatus = context.checkCallingOrSelfPermission(ANIMATION_PERMISSION);
  if (permStatus == PackageManager.PERMISSION_GRANTED) {
    setSystemAnimationsScale(DISABLED);
  }
}
 
Example 17
Project: quickstart-android   File: UiAutomatorTest.java   View source code 6 votes vote down vote up
@Before
public void setUp() {
    // Get the device instance
    mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    assertThat(mDevice, notNullValue());

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

    // Launch the app
    Context context = InstrumentationRegistry.getContext();
    Intent intent = new Intent()
            .setClassName(APP_PACKAGE, APP_PACKAGE + ".MainActivity")
            .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);

    // Wait for the app to appear
    mDevice.wait(Until.hasObject(By.pkg(APP_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
    mContext = InstrumentationRegistry.getTargetContext();
}
 
Example 18
Project: AsteroidOSSync   File: UIUtil.java   View source code 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 19
Project: AsteroidOSSync   File: UIUtil.java   View source code 6 votes vote down vote up
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");
    }
}
 
Example 20
Project: android_packages_apps_tv   File: UiDeviceUtils.java   View source code 6 votes vote down vote up
public static void pressDpad(UiDevice uiDevice, Direction direction) {
    switch (direction) {
        case UP:
            uiDevice.pressDPadUp();
            break;
        case DOWN:
            uiDevice.pressDPadDown();
            break;
        case LEFT:
            uiDevice.pressDPadLeft();
            break;
        case RIGHT:
            uiDevice.pressDPadRight();
            break;
        default:
            throw new IllegalArgumentException(direction.toString());
    }
}
 
Example 21
Project: aken-ajalukku   File: ApplicationTest.java   View source code 6 votes vote down vote up
@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 = device.getLauncherPackageName();
    assertThat(launcherPackage, notNullValue());
    device.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), 5000);
    // Launch the app
    Context context = InstrumentationRegistry.getContext();
    final Intent intent = context.getPackageManager()
            .getLaunchIntentForPackage(APP_PACKAGE);
    // Clear out any previous instances
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);
    allowPermissionsIfNeeded();
    // Wait for the app to appear

    assertTrue("Failed to find map", device.wait(Until.hasObject(By.res(APP_PACKAGE, "map")), 30000));
}
 
Example 22
Project: NineSquare   File: UiAutoTest.java   View source code 6 votes vote down vote up
@Before
public void startMainActivityFromHomeScreen() throws IOException, RemoteException {
    mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    mDevice.pressHome();

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

    Context context = InstrumentationRegistry.getContext();
    Intent i = context.getPackageManager()
            .getLaunchIntentForPackage(PACKAGE_NAME);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(i);

    // Wait for the app to appear
    mDevice.wait(Until.hasObject(By.pkg(PACKAGE_NAME).depth(0)), 5000);
}
 
Example 23
Project: notification-adapter   File: NotificationAdapterTest.java   View source code 5 votes vote down vote up
@Test
public void testNotificationAdapter() {
    final String NOTIFICATION_TEXT = "adapter-text";
    final String NOTIFICATION_TITLE = "adapter-title";
    final long TIMEOUT = 5000;

    Context appContext = InstrumentationRegistry.getTargetContext();

    RemoteViews contentView = new RemoteViews("cn.dreamtobe.toolset.test", R.layout.custom_layout);
    contentView.setTextViewText(R.id.title, NOTIFICATION_TITLE);
    contentView.setTextViewText(R.id.text, NOTIFICATION_TEXT);

    // Fix the Notification-Style problem ---------------
    // Set the default title style color to title view.
    contentView.setTextColor(R.id.title, NotificationAdapter.getTitleColor(appContext));
    // Set the default title style size to title view
    contentView.setTextViewTextSize(R.id.title, COMPLEX_UNIT_PX, NotificationAdapter.getTitleSize(appContext));
    // Set the default text style color to text view
    contentView.setTextColor(R.id.text, NotificationAdapter.getTextColor(appContext));
    // Set the default text style size to text view
    contentView.setTextViewTextSize(R.id.text, COMPLEX_UNIT_PX, NotificationAdapter.getTextSize(appContext));
    // End fix the Notification-Style problem ---------------

    Notification notification = new Notification();
    notification.icon = R.drawable.ic_launcher;
    notification.contentView = contentView;

    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.defaults |= Notification.DEFAULT_VIBRATE;

    NotificationManager notifyMgr =
            (NotificationManager) appContext.getSystemService(NOTIFICATION_SERVICE);
    notifyMgr.notify(1, notification);

    UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    device.openNotification();
    device.wait(Until.hasObject(By.text(NOTIFICATION_TITLE)), TIMEOUT);
}
 
Example 24
Project: adyen-android   File: PaymentAppTest.java   View source code 5 votes vote down vote up
@Before
public void setUp() throws Throwable {
    UiDevice.getInstance(getInstrumentation()).wakeUp();
    Intent intent = new Intent(getTargetContext(), MainActivity.class);
    mainActivityRule.launchActivity(intent);
    mainActivityRule.getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
 
Example 25
Project: adyen-android   File: PaymentAppTest.java   View source code 5 votes vote down vote up
/**
 * This test needs additional work. The following passes in Google Pixel device. But since
 * it uses screen coordinates; this test cannot be relied on yet. Work in progress.
 * @throws Exception
 */
@Ignore @Test
public void testIdealPayment() throws Exception {
    startIdealPayment();
    waitForText("Test Issuer");
    onView(withText(equalToIgnoringCase("Test Issuer"))).perform(click());
    final UiDevice device = UiDevice.getInstance(getInstrumentation());
    Thread.sleep(5000);
    device.click(65, 535);

    checkResultString(Payment.PaymentStatus.AUTHORISED.toString());
}
 
Example 26
Project: civify-app   File: CreateIssueActivityTest.java   View source code 5 votes vote down vote up
private static void takeCameraPhoto() throws UiObjectNotFoundException {
    UiDevice device = UiDevice.getInstance(getInstrumentation());
    UiSelector shutterSelector =
            new UiSelector().resourceId("com.android.camera:id/shutter_button");
    UiObject shutterButton = device.findObject(shutterSelector);
    shutterButton.click();

    UiSelector doneSelector = new UiSelector().resourceId("com.android.camera:id/btn_done");
    UiObject doneButton = device.findObject(doneSelector);
    doneButton.click();
}
 
Example 27
Project: ChimpCheck   File: PermissionGranter.java   View source code 5 votes vote down vote up
public static void allowPermissionsIfNeeded() {
    if (Build.VERSION.SDK_INT >= 23) {
        UiDevice device = UiDevice.getInstance(getInstrumentation());
        UiObject allowPermissions = device.findObject(new UiSelector().text("Allow"));
        if (allowPermissions.exists()) {
            try {
                allowPermissions.click();
            } catch (UiObjectNotFoundException e) {
                Log.e(e.getStackTrace()[0].toString(), "There is no permissions dialog to interact with ");
            }
        }
    }
}
 
Example 28
Project: ChimpCheck   File: EspressoChimpDriver.java   View source code 5 votes vote down vote up
@Override
protected void launchClickHome() {
    Log.i(runner.chimpTag("[email protected]"), "ClickHome");

    // Espresso.onView(isRoot()).perform( new ChimpStagingAction() );

    UiDevice mDevice = UiDevice.getInstance(getInstrumentation());
    mDevice.pressHome();

    // Espresso.onView(isRoot()).perform(pressKey(KeyEvent.KEYCODE_HOME));
    // kickBackExperiment();
}
 
Example 29
Project: ChimpCheck   File: EspressoChimpDriver.java   View source code 5 votes vote down vote up
@Override
protected void launchClickBack() {
    Log.i(runner.chimpTag("[email protected]"), "ClickBack");
    UiDevice mDevice = UiDevice.getInstance(getInstrumentation());
    mDevice.pressBack();


}
 
Example 30
Project: chaosflix-leanback   File: ConferencesActivityTest.java   View source code 5 votes vote down vote up
@Before
public void setup() throws IOException, TimeoutException {
	mDevice = UiDevice.getInstance(getInstrumentation());

	server = new MockWebServer();
	server.start();
	String serverUrl = server.url("").toString();

	server.enqueue(TestHelper.getResponseForRaw(R.raw.conferences_json));
	server.enqueue(TestHelper.getResponseForRaw(R.raw.conferences_101_33c3_json));

	Intent i = new Intent();
	i.putExtra("server_url",serverUrl);
	mActivityTestRule.launchActivity(i);
}
 
Example 31
Project: orgzly-android   File: ListWidgetTest.java   View source code 5 votes vote down vote up
@Before
public void addWidget() throws Exception {
    device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

    device.pressHome();
    device.pressHome();
}
 
Example 32
Project: chaosflix   File: ConferencesActivityTest.java   View source code 5 votes vote down vote up
@Before
public void setup() throws IOException, TimeoutException {
	mDevice = UiDevice.getInstance(getInstrumentation());

	server = new MockWebServer();
	server.start();
	String serverUrl = server.url("").toString();

	server.enqueue(TestHelper.getResponseForRaw(R.raw.conferences_json));
	server.enqueue(TestHelper.getResponseForRaw(R.raw.conferences_101_33c3_json));

	Intent i = new Intent();
	i.putExtra("server_url",serverUrl);
	mActivityTestRule.launchActivity(i);
}
 
Example 33
Project: smart-lens   File: ModelDownloadingNotificationTest.java   View source code 5 votes vote down vote up
@Before
public void init() {
    mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

    //Open notification drawer
    mDevice.openNotification();
    mDevice.wait(Until.hasObject(By.pkg("com.android.systemui")), 10000);
}
 
Example 34
Project: dagger-test-example   File: SimpleEspressoTest.java   View source code 5 votes vote down vote up
protected void allowPermissionsIfNeeded()  {
    if (Build.VERSION.SDK_INT >= 23) {
        UiObject allowPermissions = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()).findObject(
                new UiSelector().className("android.widget.Button")
                                .resourceId("com.android.packageinstaller:id/permission_allow_button"));
        if (allowPermissions.exists()) {
            try {
                allowPermissions.click();
            } catch (UiObjectNotFoundException e) {
                Log.e(this.getClass().getName(), "There is no permissions dialog to interact with ", e);
            }
        }
    }
}
 
Example 35
Project: FlickLauncher   File: RotationPreferenceTest.java   View source code 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();

    mDevice = UiDevice.getInstance(getInstrumentation());
    mTargetContext = getInstrumentation().getTargetContext();
    mTargetPackage = mTargetContext.getPackageName();
    mPrefs = Utilities.getPrefs(mTargetContext);
    mOriginalRotationValue = mPrefs.getBoolean(Utilities.ALLOW_ROTATION_PREFERENCE_KEY, false);
}
 
Example 36
Project: FlickLauncher   File: LauncherInstrumentationTestCase.java   View source code 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();

    mDevice = UiDevice.getInstance(getInstrumentation());
    mTargetContext = getInstrumentation().getTargetContext();
    mTargetPackage = mTargetContext.getPackageName();
}
 
Example 37
Project: UIAutomatorWD   File: UIAutomatorWD.java   View source code 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 38
Project: UIAutomatorAdapter   File: AutoTestAdapter.java   View source code 5 votes vote down vote up
private void stopApp(UiDevice device, String app) {
    String stopCmd = "am force-stop " + app + "\n";
    try {
        device.executeShellCommand(stopCmd);
        appName = null;
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 39
Project: UIAutomatorAdapter   File: AutoTestAdapter.java   View source code 5 votes vote down vote up
@Before
public void setUp() throws IOException, RemoteException {
    // Initialize UiDevice instance
    mDevice = UiDevice.getInstance(getInstrumentation());
    // wake up the device when screen is off
    if (!mDevice.isScreenOn()) {
        mDevice.wakeUp();
        mDevice.swipe(mDevice.getDisplayWidth() / 2,
                mDevice.getDisplayHeight() - 100, mDevice.getDisplayWidth() / 2,
                mDevice.getDisplayHeight() / 2, 5);
        delay(1000);
        preSteup(); // do wakeup & maybe unlock gesture lock
    }
    // Start from the home screen
    mDevice.pressHome();
    // launch "com.sc.uiautomatoradapter" to grant the permission and copy XML file to SDCARD
    launchPackage("com.sc.uiautomatoradapter");

    UiObject2 allow = mDevice.wait(Until.findObject(By.res(
            "com.android.packageinstaller:id/permission_allow_button")), timeout);
    // click the allow button to grant the permission
    if (allow != null && allow.isClickable()) {
        allow.click();
        delay(5000);
    }
    if (logger.mOut == null || parser.apps == null) {
        // initialize the Logger instance
        logger.init();
        // initialize the XMLParser instance
        parser.init();
    }
}
 
Example 40
Project: SimpleUILauncher   File: RotationPreferenceTest.java   View source code 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();

    mDevice = UiDevice.getInstance(getInstrumentation());
    mTargetContext = getInstrumentation().getTargetContext();
    mTargetPackage = mTargetContext.getPackageName();
    mPrefs = Utilities.getPrefs(mTargetContext);
    mOriginalRotationValue = mPrefs.getBoolean(Utilities.ALLOW_ROTATION_PREFERENCE_KEY, false);
}