@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); }); }
@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); }
@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); }
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"); } }
@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(); }
@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); }
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; }
/** * 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."); } }
@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); }
/** * 测试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(); }
/** * 滑动界面,打开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(); }
@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()); } }
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; }
@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()); } }
@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(); }
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); } }
@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(); }
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"); } }
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()); } }
@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)); }
@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); }
@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); }
@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); }
/** * 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()); }
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(); }
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 "); } } } }
@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); }
@Before public void addWidget() throws Exception { device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); device.pressHome(); device.pressHome(); }
@Before public void init() { mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); //Open notification drawer mDevice.openNotification(); mDevice.wait(Until.hasObject(By.pkg("com.android.systemui")), 10000); }
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); } } } }
@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); }
@Override protected void setUp() throws Exception { super.setUp(); mDevice = UiDevice.getInstance(getInstrumentation()); mTargetContext = getInstrumentation().getTargetContext(); mTargetPackage = mTargetContext.getPackageName(); }
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()); } }
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(); } }
@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(); } }