How to use executeAdbCommand method of com.qaprosoft.carina.core.foundation.utils.android.IAndroidUtils class

Best Carina code snippet using com.qaprosoft.carina.core.foundation.utils.android.IAndroidUtils.executeAdbCommand

Source:IAndroidUtils.java Github

copy

Full Screen

...171 String setLocalizationChangePermissionCmd = "shell pm grant net.sanapeli.adbchangelanguage android.permission.CHANGE_CONFIGURATION";172 String setLocalizationCmd = "shell am start -n net.sanapeli.adbchangelanguage/.AdbChangeLanguage -e language "173 + language;174 UTILS_LOGGER.info("Try set localization change permission with following cmd:" + setLocalizationChangePermissionCmd);175 String expandOutput = executeAdbCommand(setLocalizationChangePermissionCmd);176 String pathToInstalledAppCmd = "shell pm path net.sanapeli.adbchangelanguage";177 String pathToInstalledApp = executeAdbCommand(pathToInstalledAppCmd);178 if (expandOutput.contains("Unknown package: net.sanapeli.adbchangelanguage") || pathToInstalledApp.isEmpty()) {179 UTILS_LOGGER.info("Looks like 'ADB Change Language apk' is not installed. Install it and try again.");180 installApk(LANGUAGE_CHANGE_APP_PATH, true);181 expandOutput = executeAdbCommand(setLocalizationChangePermissionCmd);182 }183 UTILS_LOGGER.info("Output after set localization change permission using 'ADB Change Language apk': " + expandOutput);184 UTILS_LOGGER.info("Try set localization to '" + language + "' with following cmd: " + setLocalizationCmd);185 String changeLocaleOutput = executeAdbCommand(setLocalizationCmd);186 UTILS_LOGGER.info("Output after set localization to '" + language + "' using 'ADB Change Language apk' : "187 + changeLocaleOutput);188 if (waitTime > 0) {189 UTILS_LOGGER.info("Wait for at least '" + waitTime + "' seconds before device refresh.");190 CommonUtils.pause(waitTime);191 }192 actualDeviceLanguage = getDeviceLanguage();193 UTILS_LOGGER.info("Actual Device Language: " + actualDeviceLanguage);194 if (language.contains(actualDeviceLanguage.toLowerCase())195 || actualDeviceLanguage.toLowerCase().contains(language)) {196 status = true;197 } else {198 if (getDeviceLanguage().isEmpty()) {199 UTILS_LOGGER.info("Adb return empty response without errors.");200 status = true;201 } else {202 String currentAndroidVersion = IDriverPool.getDefaultDevice().getOsVersion();203 UTILS_LOGGER.info("currentAndroidVersion=" + currentAndroidVersion);204 if (currentAndroidVersion.contains("7.")) {205 UTILS_LOGGER.info("Adb return language command do not work on some Android 7+ devices."206 + " Check that there are no error.");207 status = !getDeviceLanguage().toLowerCase().contains("error");208 }209 }210 }211 return status;212 }213 /**214 * getDeviceLanguage215 *216 * @return String217 */218 default public String getDeviceLanguage() {219 String locale = executeAdbCommand("shell getprop persist.sys.language");220 if (locale.isEmpty()) {221 locale = executeAdbCommand("shell getprop persist.sys.locale");222 }223 return locale;224 }225 // End Language Change section226 /**227 * install android Apk by path to apk file.228 *229 * @param apkPath230 * String231 */232 default public void installApk(final String apkPath) {233 installApk(apkPath, false);234 }235 /**236 * install android Apk by path to apk or by name in classpath.237 *238 * @param apkPath239 * String240 * @param inClasspath241 * boolean242 */243 default public void installApk(final String apkPath, boolean inClasspath) {244 String filePath = apkPath;245 if (inClasspath) {246 URL baseResource = ClassLoader.getSystemResource(apkPath);247 if (baseResource == null) {248 throw new RuntimeException("Unable to get resource from classpath: " + apkPath);249 } else {250 UTILS_LOGGER.debug("Resource was found: " + baseResource.getPath());251 }252 String fileName = FilenameUtils.getBaseName(baseResource.getPath()) + "."253 + FilenameUtils.getExtension(baseResource.getPath());254 // make temporary copy of resource in artifacts folder255 filePath = ReportContext.getArtifactsFolder().getAbsolutePath() + File.separator + fileName;256 File file = new File(filePath);257 if (!file.exists()) {258 InputStream link = (ClassLoader.getSystemResourceAsStream(apkPath));259 try {260 Files.copy(link, file.getAbsoluteFile().toPath());261 } catch (IOException e) {262 UTILS_LOGGER.error("Unable to extract resource from ClassLoader!", e);263 }264 }265 }266 executeAdbCommand("install " + filePath);267 }268 public enum SelectorType {269 TEXT,270 TEXT_CONTAINS,271 TEXT_STARTS_WITH,272 ID,273 DESCRIPTION,274 DESCRIPTION_CONTAINS,275 CLASS_NAME276 }277 /**278 * Scrolls into view in specified container by text only and return boolean279 *280 * @param container281 * ExtendedWebElement - defaults to id Selector Type282 * @param scrollToElement283 * String defaults to text Selector Type284 * @return ExtendedWebElement285 * <p>286 * example of usage: ExtendedWebElement res =287 * AndroidUtils.scroll("News", newsListContainer);288 **/289 default public ExtendedWebElement scroll(String scrollToElement, ExtendedWebElement container) {290 return scroll(scrollToElement, container, SelectorType.ID, SelectorType.TEXT);291 }292 /**293 * Scrolls into view in a container specified by it's instance (index)294 * 295 * @param scrollToEle296 * - has to be id, text, contentDesc or className297 * @param scrollableContainer298 * - ExtendedWebElement type299 * @param containerSelectorType300 * - has to be id, text, textContains, textStartsWith, Description,301 * DescriptionContains or className302 * @param containerInstance303 * - has to an instance number of desired container304 * @param eleSelectorType305 * - has to be id, text, textContains, textStartsWith, Description,306 * DescriptionContains or className307 * @return ExtendedWebElement308 * <p>309 * example of usage: ExtendedWebElement res =310 * AndroidUtils.scroll("News", newsListContainer,311 * AndroidUtils.SelectorType.CLASS_NAME, 1,312 * AndroidUtils.SelectorType.TEXT);313 **/314 default public ExtendedWebElement scroll(String scrollToEle, ExtendedWebElement scrollableContainer,315 SelectorType containerSelectorType, int containerInstance, SelectorType eleSelectorType) {316 ExtendedWebElement extendedWebElement = null;317 long startTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());318 // TODO: support multi threaded WebDriver's removing DriverPool usage319 WebDriver drv = castDriver();320 // workaorund for appium issue: https://github.com/appium/appium/issues/10159321 if (scrollToEle.contains(",")) {322 scrollToEle = StringUtils.join(StringUtils.split(scrollToEle, ","), ",", 0, 2);323 if (eleSelectorType.equals(SelectorType.TEXT)) {324 eleSelectorType = SelectorType.TEXT_CONTAINS;325 }326 }327 for (int i = 0; i < SCROLL_MAX_SEARCH_SWIPES; i++) {328 try {329 By scrollBy = MobileBy.AndroidUIAutomator("new UiScrollable("330 + getScrollContainerSelector(scrollableContainer, containerSelectorType) + ".instance("331 + containerInstance + "))" + ".setMaxSearchSwipes(" + SCROLL_MAX_SEARCH_SWIPES + ")"332 + ".scrollIntoView(" + getScrollToElementSelector(scrollToEle, eleSelectorType) + ")");333 WebElement ele = drv.findElement(scrollBy);334 if (ele.isDisplayed()) {335 UTILS_LOGGER.info("Element found!!!");336 // initializing with driver context because scrollBy consists from container and element selectors337 extendedWebElement = new ExtendedWebElement(scrollBy, scrollToEle, drv, drv);338 break;339 }340 } catch (NoSuchElementException noSuchElement) {341 UTILS_LOGGER.error(String.format("%s %s:%s", SpecialKeywords.NO_SUCH_ELEMENT_ERROR, eleSelectorType, scrollToEle),342 noSuchElement);343 }344 for (int j = 0; j < i; j++) {345 checkTimeout(startTime);346 MobileBy.AndroidUIAutomator(347 "new UiScrollable(" + getScrollContainerSelector(scrollableContainer, containerSelectorType)348 + ".instance(" + containerInstance + ")).scrollForward()");349 UTILS_LOGGER.info("Scroller got stuck on a page, scrolling forward to next page of elements..");350 }351 }352 return extendedWebElement;353 }354 /**355 * Scrolls into view in specified container356 * 357 * @param scrollToEle358 * - has to be id, text, contentDesc or className359 * @param scrollableContainer360 * - ExtendedWebElement type361 * @param containerSelectorType362 * - has to be id, text, textContains, textStartsWith, Description,363 * DescriptionContains or className364 * @param containerInstance365 * - has to an instance number of desired container366 * @param eleSelectorType367 * - has to be id, text, textContains, textStartsWith, Description,368 * DescriptionContains or className369 * @param eleSelectorInstance370 * - has to an instance number of desired container371 * @return ExtendedWebElement372 * <p>373 * example of usage: ExtendedWebElement res =374 * AndroidUtils.scroll("News", newsListContainer,375 * AndroidUtils.SelectorType.CLASS_NAME, 1,376 * AndroidUtils.SelectorType.TEXT, 2);377 **/378 default public ExtendedWebElement scroll(String scrollToEle, ExtendedWebElement scrollableContainer,379 SelectorType containerSelectorType, int containerInstance, SelectorType eleSelectorType,380 int eleSelectorInstance) {381 ExtendedWebElement extendedWebElement = null;382 long startTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());383 // TODO: support multi threaded WebDriver's removing DriverPool usage384 WebDriver drv = castDriver();385 // workaorund for appium issue: https://github.com/appium/appium/issues/10159386 if (scrollToEle.contains(",")) {387 scrollToEle = StringUtils.join(StringUtils.split(scrollToEle, ","), ",", 0, 2);388 if (eleSelectorType.equals(SelectorType.TEXT)) {389 eleSelectorType = SelectorType.TEXT_CONTAINS;390 }391 }392 for (int i = 0; i < SCROLL_MAX_SEARCH_SWIPES; i++) {393 try {394 By scrollBy = MobileBy.AndroidUIAutomator("new UiScrollable("395 + getScrollContainerSelector(scrollableContainer, containerSelectorType) + ".instance("396 + containerInstance + "))" + ".setMaxSearchSwipes(" + SCROLL_MAX_SEARCH_SWIPES + ")"397 + ".scrollIntoView(" + getScrollToElementSelector(scrollToEle, eleSelectorType) + ".instance("398 + eleSelectorInstance + "))");399 WebElement ele = drv.findElement(scrollBy);400 if (ele.isDisplayed()) {401 UTILS_LOGGER.info("Element found!!!");402 // initializing with driver context because scrollBy consists from container and element selectors403 extendedWebElement = new ExtendedWebElement(scrollBy, scrollToEle, drv, drv);404 break;405 }406 } catch (NoSuchElementException noSuchElement) {407 UTILS_LOGGER.error(String.format("%s%s:%s", SpecialKeywords.NO_SUCH_ELEMENT_ERROR, eleSelectorType, scrollToEle),408 noSuchElement);409 }410 for (int j = 0; j < i; j++) {411 checkTimeout(startTime);412 MobileBy.AndroidUIAutomator(413 "new UiScrollable(" + getScrollContainerSelector(scrollableContainer, containerSelectorType)414 + ".instance(" + containerInstance + ")).scrollForward()");415 UTILS_LOGGER.info("Scroller got stuck on a page, scrolling forward to next page of elements..");416 }417 }418 return extendedWebElement;419 }420 /**421 * Scrolls into view in specified container422 * 423 * @param scrollToEle424 * - has to be id, text, contentDesc or className425 * @param scrollableContainer426 * - ExtendedWebElement type427 * @param containerSelectorType428 * - container Selector type: has to be id, text, textContains,429 * textStartsWith, Description, DescriptionContains or className430 * @param eleSelectorType431 * - scrollToEle Selector type: has to be id, text, textContains,432 * textStartsWith, Description, DescriptionContains or className433 * @return ExtendedWebElement434 * <p>435 * example of usage: ExtendedWebElement res =436 * AndroidUtils.scroll("News", newsListContainer,437 * AndroidUtils.SelectorType.CLASS_NAME,438 * AndroidUtils.SelectorType.TEXT);439 **/440 default public ExtendedWebElement scroll(String scrollToEle, ExtendedWebElement scrollableContainer,441 SelectorType containerSelectorType, SelectorType eleSelectorType) {442 ExtendedWebElement extendedWebElement = null;443 long startTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());444 // TODO: support multi threaded WebDriver's removing DriverPool usage445 WebDriver drv = castDriver();446 // workaorund for appium issue: https://github.com/appium/appium/issues/10159447 if (scrollToEle.contains(",")) {448 scrollToEle = StringUtils.join(StringUtils.split(scrollToEle, ","), ",", 0, 2);449 if (eleSelectorType.equals(SelectorType.TEXT)) {450 eleSelectorType = SelectorType.TEXT_CONTAINS;451 }452 }453 for (int i = 0; i < SCROLL_MAX_SEARCH_SWIPES; i++) {454 try {455 By scrollBy = MobileBy.AndroidUIAutomator(456 "new UiScrollable(" + getScrollContainerSelector(scrollableContainer, containerSelectorType)457 + ")" + ".setMaxSearchSwipes(" + SCROLL_MAX_SEARCH_SWIPES + ")" + ".scrollIntoView("458 + getScrollToElementSelector(scrollToEle, eleSelectorType) + ")");459 WebElement ele = drv.findElement(scrollBy);460 if (ele.isDisplayed()) {461 UTILS_LOGGER.info("Element found!!!");462 // initializing with driver context because scrollBy consists from container and element selectors463 extendedWebElement = new ExtendedWebElement(scrollBy, scrollToEle, drv, drv);464 break;465 }466 } catch (NoSuchElementException noSuchElement) {467 UTILS_LOGGER.error(String.format("%s%s:%s", SpecialKeywords.NO_SUCH_ELEMENT_ERROR, eleSelectorType, scrollToEle),468 noSuchElement);469 }470 for (int j = 0; j < i; j++) {471 checkTimeout(startTime);472 MobileBy.AndroidUIAutomator("new UiScrollable("473 + getScrollContainerSelector(scrollableContainer, containerSelectorType) + ").scrollForward()");474 UTILS_LOGGER.info("Scroller got stuck on a page, scrolling forward to next page of elements..");475 }476 }477 return extendedWebElement;478 }479 /**480 * Scrolls into view in specified container481 * 482 * @param scrollableContainer483 * - ExtendedWebElement type484 * @param containerSelectorType485 * - Selector type: has to be id, text, contentDesc or className486 * @return scrollViewContainerFinder String487 *488 **/489 default String getScrollContainerSelector(ExtendedWebElement scrollableContainer,490 SelectorType containerSelectorType) {491 UTILS_LOGGER.debug(scrollableContainer.getBy().toString());492 String scrollableContainerBy;493 String scrollViewContainerFinder = "";494 switch (containerSelectorType) {495 case TEXT:496 scrollableContainerBy = scrollableContainer.getBy().toString().replace("By.text:", "").trim();497 scrollViewContainerFinder = "new UiSelector().text(\"" + scrollableContainerBy + "\")";498 break;499 case TEXT_CONTAINS:500 scrollableContainerBy = scrollableContainer.getBy().toString().replace("By.textContains:", "").trim();501 scrollViewContainerFinder = "new UiSelector().textContains(\"" + scrollableContainerBy + "\")";502 break;503 case TEXT_STARTS_WITH:504 scrollableContainerBy = scrollableContainer.getBy().toString().replace("By.textStartsWith:", "").trim();505 scrollViewContainerFinder = "new UiSelector().textStartsWith(\"" + scrollableContainerBy + "\")";506 break;507 case ID:508 scrollableContainerBy = scrollableContainer.getBy().toString().replace("By.id:", "").trim();509 scrollViewContainerFinder = "new UiSelector().resourceId(\"" + scrollableContainerBy + "\")";510 break;511 case DESCRIPTION:512 scrollableContainerBy = scrollableContainer.getBy().toString().replace("By.description:", "").trim();513 scrollViewContainerFinder = "new UiSelector().description(\"" + scrollableContainerBy + "\")";514 break;515 case DESCRIPTION_CONTAINS:516 scrollableContainerBy = scrollableContainer.getBy().toString().replace("By.descriptionContains:", "")517 .trim();518 scrollViewContainerFinder = "new UiSelector().descriptionContains(\"" + scrollableContainerBy + "\")";519 break;520 case CLASS_NAME:521 scrollableContainerBy = scrollableContainer.getBy().toString().replace("By.className:", "").trim();522 scrollViewContainerFinder = "new UiSelector().className(\"" + scrollableContainerBy + "\")";523 break;524 default:525 UTILS_LOGGER.info("Please provide valid selectorType for element to be found...");526 break;527 }528 return scrollViewContainerFinder;529 }530 /**531 * Scrolls into view in specified container532 * 533 * @param scrollToEle534 * - String type535 * @param eleSelectorType536 * - Selector type: has to be id, text, contentDesc or className537 * @return String538 **/539 default String getScrollToElementSelector(String scrollToEle, SelectorType eleSelectorType) {540 String neededElementFinder = "";541 String scrollToEleTrimmed;542 switch (eleSelectorType) {543 case TEXT:544 neededElementFinder = "new UiSelector().text(\"" + scrollToEle + "\")";545 break;546 case TEXT_CONTAINS:547 neededElementFinder = "new UiSelector().textContains(\"" + scrollToEle + "\")";548 break;549 case TEXT_STARTS_WITH:550 neededElementFinder = "new UiSelector().textStartsWith(\"" + scrollToEle + "\")";551 break;552 case ID:553 scrollToEleTrimmed = scrollToEle.replace("By.id:", "").trim();554 neededElementFinder = "new UiSelector().resourceId(\"" + scrollToEleTrimmed + "\")";555 break;556 case DESCRIPTION:557 neededElementFinder = "new UiSelector().description(\"" + scrollToEle + "\")";558 break;559 case DESCRIPTION_CONTAINS:560 neededElementFinder = "new UiSelector().descriptionContains(\"" + scrollToEle + "\")";561 break;562 case CLASS_NAME:563 scrollToEleTrimmed = scrollToEle.replace("By.className:", "").trim();564 neededElementFinder = "new UiSelector().className(\"" + scrollToEleTrimmed + "\")";565 break;566 default:567 UTILS_LOGGER.info("Please provide valid selectorType for element to be found...");568 break;569 }570 return neededElementFinder;571 }572 /**573 * Scroll Timeout check574 * 575 * @param startTime576 * - Long initial time for timeout count down577 **/578 default public void checkTimeout(long startTime) {579 long elapsed = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()) - startTime;580 if (elapsed > SCROLL_TIMEOUT) {581 throw new NoSuchElementException("Scroll timeout has been reached..");582 }583 }584 /**585 * getCurrentDeviceFocus - get actual device apk in focus.586 *587 * @return String588 */589 default public String getCurrentDeviceFocus() {590 String result = executeAdbCommand("shell dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'");591 return result;592 }593 /**594 * executeAbdCommand595 *596 * @param command597 * String598 * @return String command output in one line599 */600 default public String executeAdbCommand(String command) {601 String deviceName = getDevice().getAdbName();602 if (!deviceName.isEmpty()) {603 // add remoteURL/udid reference604 command = "-s " + deviceName + " " + command;605 } else {606 UTILS_LOGGER.warn("nullDevice detected fot current thread!");607 }608 String result = "";609 UTILS_LOGGER.info("Command: " + command);610 String[] listOfCommands = command.split(" ");611 String[] execCmd = CmdLine.insertCommandsAfter(baseInitCmd, listOfCommands);612 try {613 UTILS_LOGGER.info("Try to execute following cmd: " + CmdLine.arrayToString(execCmd));614 List<String> execOutput = executor.execute(execCmd);615 UTILS_LOGGER.info("Output after execution ADB command: " + execOutput);616 result = execOutput.toString().replaceAll("\\[|\\]", "").replaceAll(", ", " ").trim();617 UTILS_LOGGER.info("Returning Output: " + result);618 } catch (Exception e) {619 UTILS_LOGGER.error("Error while executing adb command: " + command, e);620 }621 return result;622 }623 /**624 * 625 * @param command626 * 627 * - ADB shell command represented as single String where 1st literal628 * is a command itself. Everything that follow is treated as629 * arguments.630 *631 * NOTE: "adb -s {UDID} shell" - should be omitted.632 * Example: "adb -s {UDID} shell list packages" - list packages633 * 634 * NOTE: shell arguments with space symbols are unsupported!635 * 636 * @return String - response (might be empty)637 */638 default public String executeShell(String command) {639 UTILS_LOGGER.info("ADB command to be executed: adb shell ".concat(command.trim()));640 List<String> literals = Arrays.asList(command.split(" "));641 return executeShell(literals);642 }643 /**644 * 645 * @param commands list of string commands646 * 647 * - ADB shell command represented as single String where 1st literal648 * is a command itself. Everything that follow is treated as649 * arguments.650 *651 * NOTE: "adb -s {UDID} shell" - should be omitted.652 * Example: "adb -s {UDID} shell list packages" - list packages653 * 654 * @return String - response (might be empty)655 */656 default public String executeShell(List<String> commands) {657 String commadKeyWord = commands.get(0);658 List<String> args = commands.subList(1, commands.size());659 Map<String, Object> preparedCommand = ImmutableMap.of("command", commadKeyWord, "args", args);660 String output = (String) ((AppiumDriver<?>) castDriver()).executeScript(SHELL_INIT_CONSOLE, preparedCommand);661 if (!StringUtils.isEmpty(output)) {662 UTILS_LOGGER.debug("ADB command output: " + output);663 }664 return output;665 }666 /**667 * This method performs an action corresponding to press Android device's native668 * button to show all recent applications.669 * 670 * NOTE: method could be used to get a list of running in background671 * applications with respect to particular device.672 */673 default public void displayRecentApps() {674 executeShell(SHELL_RECENT_APPS_CMD);675 }676 /**677 * Tapping at native 'Home' button will be emulated. All applications will be678 * closed to background.679 */680 default public void pressHome() {681 executeShell(SHELL_PRESS_HOME_CMD);682 }683 /**684 * Is used to get GPS service status.685 * 686 * Response reflects which services are used for obtaining location:687 * 688 * - "gps" - GPS only (device only);689 * 690 * - "gps,network" - GPS + Wi-Fi + Bluetooth or cellular networks (High accuracy691 * mode);692 * 693 * - "network" - Using Wi-Fi, Bluetooth or cellular networks (Battery saving694 * mode);695 * 696 * @return boolean697 */698 default public boolean isGPSEnabled() {699 String response = executeShell(SHELL_GPS_STATUS_CMD);700 return response.contains("gps");701 }702 default public void enableGPS() {703 executeShell(SHELL_ENABLE_GPS_CMD);704 }705 /**706 * Works if ONLY DEVICE (GPS sensor) is user for obtaining location707 */708 default public void disableGPS() {709 executeShell(SHELL_DISABLE_GPS_CMD);710 }711 /**712 * This command will save screenshot to specified folder on device's OS using713 * provided path.714 * 715 * @param filepath716 * - path to save screenshot to device's OS (/storage/emulated/0/Download/scr.png).717 */718 default public void takeScreenShot(String filepath) {719 UTILS_LOGGER.info("Screenshot will be saved to: " + filepath);720 String command = String.format(SHELL_TAKE_SCREENSHOT_CMD.concat(" %s"), filepath);721 executeShell(command);722 }723 /**724 * This method provides app's version for the app that is already installed to725 * devices, based on its package name.726 * In order to do that we search for "versionCode" parameter in system dump.727 * 728 * @param packageName String729 * 730 * @return appVersion String731 */732 default public String getAppVersion(String packageName) {733 String command = "dumpsys package ".concat(packageName);734 String output = executeShell(command);735 String versionCode = StringUtils.substringBetween(output, "versionCode=", " ");736 UTILS_LOGGER.info(String.format("Version code for '%s' package name is %s", packageName, versionCode));737 return versionCode;738 }739 /**740 * This method provides app's version name for the app that is already installed to741 * devices, based on its package name.742 * In order to do that we search for "versionName" parameter in system dump.743 * Ex. "versionCode" returns 11200050, "versionName" returns 11.2.0744 * 745 * @param packageName String746 * @return appVersion String747 */748 default public String getAppVersionName(String packageName) {749 String command = "dumpsys package ".concat(packageName);750 String output = this.executeShell(command);751 String versionName = StringUtils.substringBetween(output, "versionName=", "\n");752 UTILS_LOGGER.info(String.format("Version name for '%s' package name is %s", packageName, versionName));753 return versionName;754 }755 /**756 * To open Android device native settings757 */758 default public void openDeviceSettings() {759 executeShell(SHELL_OPEN_DEVICE_SETTINGS_CMD);760 }761 /**762 * Method to reset test specific application by package name763 * 764 * App's settings will be reset. User will be logged out. Application will be765 * closed to background.766 * 767 * @param packageName String768 */769 default public void clearAppCache(String packageName) {770 UTILS_LOGGER.info("Will clear data for the following app: " + packageName);771 String command = String.format(SHELL_CLEAR_CACHE_CMD.concat(" %s"), packageName);772 String response = executeShell(command);773 UTILS_LOGGER.info(774 String.format("Output after resetting custom application by package (%s): ", packageName) + response);775 if (!response.contains("Success")) {776 UTILS_LOGGER.warn(String.format("App data was not cleared for %s app", packageName));777 }778 }779 /**780 * With this method user is able to trigger a deeplink (link to specific place781 * within the application) or event open URL in mobile browser.782 * 783 * NOTE, that to open URL in browser, URL should starts with "https://www.{place784 * your link here}".785 * 786 * NOTE that not all deeplinks require package name.787 * 788 * @param link789 * - URL to trigger790 */791 default public void openURL(String link) {792 // TODO: #1380 make openURL call from this mobile interface in DriverHelper793 UTILS_LOGGER.info("Following link will be triggered via ADB: " + link);794 String command = String.format(SHELL_OPEN_URL_CMD.concat(" %s"), link);795 executeShell(command);796 }797 /**798 * With this method user is able to trigger a deeplink (link to specific place799 * within the application)800 * 801 * @param link String802 * @param packageName String803 */804 default public void triggerDeeplink(String link, String packageName) {805 Map<String, Object> preparedCommand = ImmutableMap.of("url", link, "package", packageName);806 try {807 ((AppiumDriver<?>) castDriver()).executeScript(SHELL_INIT_DEEPLINK_CONSOLE, preparedCommand);808 } catch (WebDriverException wde) {809 // TODO: need to pay attention810 UTILS_LOGGER.warn("org.openqa.selenium.WebDriverException is caught and ignored.", wde);811 }812 }813 /**814 * To get list of granted/denied/requested permission for specified application815 * 816 * @param packageName String817 * @param type PermissionType818 * @return ArrayList String819 */820 @SuppressWarnings("unchecked")821 default public ArrayList<String> getAppPermissions(String packageName, PermissionType type) {822 Map<String, Object> preparedCommand = ImmutableMap.of("type", type.getType(), "package", packageName);823 return (ArrayList<String>) ((AppiumDriver<?>) castDriver()).executeScript(SHELL_INIT_GET_PERMISSION_CONSOLE,824 preparedCommand);825 }826 /**827 * To change (grant or revoke) application permissions.828 * 829 * @param packageName String830 * @param action PermissionAction831 * @param permissions Permission832 */833 default public void changePermissions(String packageName, PermissionAction action, Permission... permissions) {834 ArrayList<String> permissionsStr = new ArrayList<>();835 Arrays.asList(permissions).forEach(p -> permissionsStr.add(p.getPermission()));836 Map<String, Object> preparedCommand = ImmutableMap.of("action", action.getAction(), "appPackage", packageName,837 "permissions", permissionsStr);838 ((AppiumDriver<?>) castDriver()).executeScript(SHELL_INIT_CHANGE_PERMISSION_CONSOLE, preparedCommand);839 }840 /**841 * Method to enter text to ACTIVATED input field.842 * 843 * NOTE: that it might be necessary to escape some special characters.844 * Space-symbol is already escaped.845 * 846 * NOTE2: input field should be cleared previously.847 * 848 * @param text String849 */850 default public void typeWithADB(String text) {851 UTILS_LOGGER.info(String.format("Will enter '%s' to an active input field via ADB.", text));852 // In this method characters are entered one by one because sometimes some853 // characters might be omitted if to enter whole text at a time.854 char[] array = text.toCharArray();855 for (char sym : array) {856 String ch = (sym == ' ') ? "%s" : String.valueOf(sym);857 String command = SHELL_INPUT_TXT_CMD + ch;858 executeShell(command);859 }860 }861 default public boolean isWifiEnabled() {862 boolean enabled = ((AndroidDriver<?>) castDriver()).getConnection().isWiFiEnabled();863 UTILS_LOGGER.info("Wi-Fi enabled: " + enabled);864 return enabled;865 }866 default public void enableWifi() {867 boolean enabled = isWifiEnabled();868 if (!enabled) {869 ((AndroidDriver<?>) castDriver()).toggleWifi();870 return;871 }872 UTILS_LOGGER.info("Wifi is already anebled. No actions needed");873 }874 default public void disableWifi() {875 boolean enabled = isWifiEnabled();876 if (enabled) {877 ((AndroidDriver<?>) castDriver()).toggleWifi();878 return;879 }880 UTILS_LOGGER.info("Wifi is already disabled. No actions needed");881 }882 /**883 * Method enters an App's menu within device System Settings884 * 885 * @param appName - Name of the app as it appears in the device's Apps list (Language specific)886 */887 default void openAppMenuFromDeviceSettings(String appName) {888 AndroidService androidService = AndroidService.getInstance();889 androidService.executeAdbCommand("shell am start -a android.settings.APPLICATION_SETTINGS");890 // initializing appItem with ExtendedWebElement constructor that initialize search context891 ExtendedWebElement appItem = new ExtendedWebElement(By.xpath(String.format("//*[contains(@text, '%s')]", appName)), "notifications",892 getDriver(), getDriver());893 swipe(appItem);894 appItem.click();895 }896 /**897 * Toggles a specified app's ability to recieve Push Notifications on the system level898 * 899 * @param appName - The app name as it appears within device System Settings900 * @param setValue - The value you wish to set the toggle to901 */902 default void toggleAppNotificationsFromDeviceSettings(String appName, boolean setValue) {903 openAppMenuFromDeviceSettings(appName);904 WebDriver driver = getDriver();905 // initializing with driver context906 ExtendedWebElement element = new ExtendedWebElement(By.xpath("//*[contains(@text, 'Notifications') or contains(@text, 'notifications')]"),907 "notifications", driver, driver);908 element.click();909 // initializing with driver context910 element = new ExtendedWebElement(By.xpath("//*[@resource-id='com.android.settings:id/switch_text']/following-sibling::android.widget.Switch"),911 "toggle", driver, driver);912 if (Boolean.valueOf(element.getAttribute("checked")) != setValue) {913 element.click();914 }915 }916 /**917 * @return - Returns if the device in use has a running LTE connection918 */919 default boolean isCarrierConnectionAvailable() {920 AndroidService androidService = AndroidService.getInstance();921 boolean status = ((AndroidDriver) this.castDriver()).getConnection().isDataEnabled();922 boolean linkProperties = false;923 String linkProp = androidService.executeAdbCommand("shell dumpsys telephony.registry | grep mPreciseDataConnectionState");924 UTILS_LOGGER.info("PROP: " + linkProp);925 if (!linkProp.isEmpty()) {926 linkProperties = !StringUtils.substringBetween(linkProp, "APN: ", " ").equals("null");927 }928 UTILS_LOGGER.info("STATUS ENABLED: " + status);929 UTILS_LOGGER.info("CARRIER AVAILABLE: " + linkProperties);930 return ((AndroidDriver) this.castDriver()).getConnection().isDataEnabled() && linkProperties;931 }932 /**933 * @return - Returns the value of the device model in use as a String934 */935 default String getDeviceModel() {936 AndroidService androidService = AndroidService.getInstance();937 return StringUtils.substringAfter(androidService.executeAdbCommand("shell getprop | grep 'ro.product.model'"), "ro.product.model: ");938 }939 default public void openStatusBar() {940 executeShell(SHELL_OPEN_STATUS_BAR_CMD);941 }942 default public void closeStatusBar() {943 executeShell(SHELL_CLOSE_STATUS_BAR_CMD);944 }945}...

Full Screen

Full Screen

Source:AndroidService.java Github

copy

Full Screen

...77 /**78 * press Home button to open home screen79 */80 public void gotoAndroidHome() {81 executeAdbCommand("shell input keyevent 3");82 }83 /**84 * openApp85 *86 * @param pkg String87 * @param activity String88 */89 public void openApp(String pkg, String activity) {90 openApp(pkg.trim() + "/" + activity.trim());91 }92 /**93 * openApp94 *95 * @param app String96 */97 public void openApp(String app) {98 String result = executeAdbCommand("shell am start -n " + app);99 if (result.contains("Exception")) {100 String appPackage = app.split("/")[0];101 if (!isAppRunning(appPackage)) {102 LOGGER.info("Expected app is not in focus. We will try another solution.");103 executeAdbCommand("shell monkey -p " + appPackage + " -c android.intent.category.LAUNCHER 1");104 }105 }106 }107 /**108 * clear Apk Cache109 *110 * @param appPackageName for example:111 * com.bamnetworks.mobile.android.gameday.atbat112 * @return boolean113 */114 public boolean clearApkCache(String appPackageName) {115 // Later can be used:116 /*117 * String packageName = executor.getApkPackageName(String apkFile);118 * executor.clearAppData(Device device, String appPackage);119 */120 String result = executeAdbCommand("shell pm clear " + appPackageName);121 if (result.contains("Success")) {122 LOGGER.info("Cache was cleared correctly");123 return true;124 } else {125 LOGGER.error("Cache was not cleared. May be application does not exist on this device.");126 return false;127 }128 }129 /**130 * get Current Focused Apk Package Name131 *132 * @return String133 */134 public String getCurrentFocusedApkPackageName() {135 String res = "";136 String txt = getCurrentDeviceFocus();137 String regEx1 = ".*?";138// String regEx2 = "((?:[a-z][a-z\\.\\d\\-]+)\\.(?:[a-z][a-z\\-]+))(?![\\w\\.])";139 Pattern pattern1 = Pattern.compile(regEx1 + regEx1, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);140 Matcher matcher1 = pattern1.matcher(txt);141 if (matcher1.find()) {142 res = matcher1.group(1);143 }144 LOGGER.info("Found package name for application in focus : " + res);145 return res;146 }147 /**148 * get Current Focused Apk Details (apkPackage/apkActivity)149 * 150 * @return apkPackage/apkActivity to use it in openApp method.151 */152 public String getCurrentFocusedApkDetails() {153 try {154 String packageName = "";155 String activityName = "";156 String txt = getCurrentDeviceFocus();157 String regEx1 = ".*?";158 String regEx2 = "((?:[a-z][a-z\\.\\d\\-]+)\\.(?:[a-z][a-z\\-]+))(?![\\w\\.])";159 Pattern pattern1 = Pattern.compile(regEx1 + regEx2, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);160 Matcher matcher1 = pattern1.matcher(txt);161 if (matcher1.find()) {162 packageName = matcher1.group(1);163 }164 LOGGER.info("Found package name for application in focus : " + packageName);165 String regEx3 = "\\/((?:[a-z][a-z\\.\\d\\-]+)\\.(?:[a-z][a-z\\-\\_]+))(?![\\w\\.])";166 Pattern pattern2 = Pattern.compile(regEx1 + regEx3, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);167 Matcher matcher2 = pattern2.matcher(txt);168 if (matcher2.find()) {169 activityName = matcher2.group(1);170 }171 LOGGER.info("Found activity name for application in focus : " + activityName);172 return packageName + "/" + activityName;173 } catch (Exception e) {174 LOGGER.error("Error during getting apk details", e);175 return "";176 }177 }178 179 /**180 * Open Development Settings on device181 */182 public void openDeveloperOptions() {183 executeAdbCommand("shell am start -n com.android.settings/.DevelopmentSettings");184 }185 // End of Common Methods186 // Notification section187 /**188 * expandStatusBar189 */190 public void expandStatusBar() {191 executeAdbCommand("shell service call statusbar 1");192 }193 /**194 * collapseStatusBar195 */196 public void collapseStatusBar() {197 executeAdbCommand("shell service call statusbar 2");198 }199 // TODO: move notifications methods into separate class if possible. Maybe200 // declare notification service instance inside AndroidService201 /**202 * getNotifications203 *204 * @return List of Notification205 */206 public List<Notification> getNotifications() {207 return getNotifications(true);208 }209 /**210 * getNotifications211 *212 * @param withLogger boolean213 * @return List of Notification214 */215 public List<Notification> getNotifications(boolean withLogger) {216 String[] getNotificationsCmd = null;217 String deviceName = IDriverPool.getDefaultDevice().getAdbName();218 if (!deviceName.isEmpty()) {219 getNotificationsCmd = CmdLine.insertCommandsAfter(baseInitCmd, "-s", deviceName, "shell", "dumpsys", "notification");220 } else {221 getNotificationsCmd = CmdLine.insertCommandsAfter(baseInitCmd, "shell", "dumpsys", "notification");222 }223 LOGGER.info("getNotifications cmd was built: " + CmdLine.arrayToString(getNotificationsCmd));224 // TODO: migrate to executeAbdCommand later225 List<Notification> resultList = new ArrayList<Notification>();226 List<String> notificationsOutput = executor.execute(getNotificationsCmd);227 Notification notification = new Notification();228 for (String output : notificationsOutput) {229 boolean found = false;230 Matcher matcher = NOTIFICATION_PATTERN.matcher(output);231 while (matcher.find()) {232 notification.setNotificationPkg(matcher.group(1));233 if (withLogger)234 LOGGER.info(matcher.group(1));235 }236 Matcher matcher2 = NOTIFICATION_TEXT_PATTERN.matcher(output);237 while (matcher2.find()) {238 notification.setNotificationText(matcher2.group(1));239 if (withLogger)240 LOGGER.info(matcher2.group(1));241 found = true;242 }243 if (found) {244 resultList.add(notification);245 if (withLogger)246 LOGGER.info(notification.getNotificationText());247 notification = new Notification();248 found = false;249 }250 }251 if (withLogger)252 LOGGER.info("Found: " + resultList.size() + " notifications.");253 return resultList;254 }255 /**256 * notificationsCount257 *258 * @return notificationsCount259 */260 public int notificationsCount() {261 List<Notification> resultList = getNotifications(false);262 LOGGER.info("Found: " + resultList.size() + " notifications.");263 return resultList.size();264 }265 /**266 * isNotificationWithTextExist267 *268 * @param text String269 * @return boolean270 */271 public boolean isNotificationWithTextExist(String text) {272 List<Notification> resultList = getNotifications(false);273 for (Notification notify : resultList) {274 if (notify.getNotificationText().contains(text)) {275 LOGGER.info("Found '" + text + "' in notification '" + notify.getNotificationText() + "'.");276 return true;277 }278 }279 return false;280 }281 /**282 * waitUntilNewNotificationAppear283 *284 * @param text String285 * @param timeout long286 * @return boolean287 */288 public boolean waitUntilNewNotificationAppear(String text, long timeout) {289 // boolean found = false;290 int base = notificationsCount();291 int time = 0;292 boolean foundText = isNotificationWithTextExist(text);293 int actual = notificationsCount();294 while (actual <= base && ++time < timeout && !foundText) {295 LOGGER.info("Wait for notification. Second: " + time + ". Actual number:" + actual);296 CommonUtils.pause(1);297 actual = notificationsCount();298 foundText = isNotificationWithTextExist(text);299 }300 return (foundText);301 }302 /**303 * isNotificationPkgExist304 *305 * @param text package text306 * @return boolean307 */308 public boolean isNotificationPkgExist(String text) {309 List<Notification> resultList = getNotifications(false);310 for (Notification notify : resultList) {311 if (notify.getNotificationPkg().contains(text)) {312 LOGGER.info("Found '" + text + "' in notification packages '" + notify.getNotificationPkg() + "' with text '"313 + notify.getNotificationText() + "'.");314 return true;315 }316 }317 return false;318 }319 /**320 * waitUntilNewNotificationPackageAppear321 *322 * @param pkg String323 * @param timeout long324 * @return boolean325 */326 public boolean waitUntilNewNotificationPackageAppear(String pkg, long timeout) {327 // boolean found = false;328 int base = notificationsCount();329 int time = 0;330 boolean foundText = isNotificationPkgExist(pkg);331 int actual = notificationsCount();332 while (actual <= base && ++time < timeout && !foundText) {333 LOGGER.info("Wait for notification. Second: " + time + ". Actual number:" + actual);334 CommonUtils.pause(1);335 actual = notificationsCount();336 foundText = isNotificationPkgExist(pkg);337 }338 return (foundText);339 }340 /**341 * find Expected Notification with partial text342 *343 * @param expectedTitle String344 * @param expectedText String345 * @return boolean346 */347 public boolean findExpectedNotification(String expectedTitle, String expectedText) {348 return findExpectedNotification(expectedTitle, expectedText, true);349 }350 /**351 * find Expected Notification352 *353 * @param expectedTitle String354 * @param expectedText String355 * @param partially boolean356 * @return boolean357 */358 @SuppressWarnings("rawtypes")359 public boolean findExpectedNotification(String expectedTitle, String expectedText, boolean partially) {360 // open notification361 try {362 ((AndroidDriver) castDriver()).openNotifications();363 CommonUtils.pause(2); // wait while notifications are playing animation to364 // appear to avoid missed taps365 } catch (Exception e) {366 LOGGER.error("Error during searching notification: " + expectedTitle, e);367 LOGGER.info("Using adb to expand Status bar. ");368 expandStatusBar();369 }370 NotificationPage nativeNotificationPage = new NotificationPage(getDriver());371 LOGGER.info("Native notification page is loaded: " + nativeNotificationPage.isNativeNotificationPage());372 int itemsListSize = nativeNotificationPage.getLastItemsContentSize();373 String title, text;374 int notificationItemNum = 0;375 for (int i = 0; i <= itemsListSize; i++) {376 title = nativeNotificationPage.getItemTitle(i);377 text = nativeNotificationPage.getItemText(i);378 LOGGER.info("Notification title is: " + title);379 LOGGER.info("Notification text is: " + text);380 if (!expectedTitle.isEmpty()) {381 if (title.equals(expectedTitle)) {382 notificationItemNum = i;383 LOGGER.info("Found expected title '" + expectedTitle + "' in notification #" + notificationItemNum);384 return true;385 } else if (partially) {386 if (expectedTitle.contains(title)) {387 notificationItemNum = i;388 LOGGER.info(389 "Found that expected title '" + expectedTitle + "' contains '" + title + "' in notification #" + notificationItemNum);390 return true;391 }392 }393 }394 if (!expectedText.isEmpty()) {395 if (text.equals(expectedText)) {396 notificationItemNum = i;397 LOGGER.info("Found expected text '" + expectedText + "' in notification #" + notificationItemNum);398 return true;399 } else if (partially) {400 if (expectedText.contains(text)) {401 notificationItemNum = i;402 LOGGER.info(403 "Found that expected text '" + expectedText + "' contains '" + text + "' in notification #" + notificationItemNum);404 return true;405 }406 }407 }408 }409 return false;410 }411 /**412 * clearNotifications413 */414 public void clearNotifications() {415 LOGGER.info("Clear notifications");416 NotificationPage notificationPage = new NotificationPage(getDriver());417 int attempts = 3;418 boolean isStatusBarOpened;419 // three attempts will be executed to clear notifications420 for (int i = 0; i < attempts; i++) {421 collapseStatusBar();422 expandStatusBar();423 // wait until status bar will be opened424 isStatusBarOpened = notificationPage.isOpened(INIT_TIMEOUT);425 if (!isStatusBarOpened) {426 LOGGER.info(String.format("Status bar isn't opened after %d seconds. One more attempt.", (int) INIT_TIMEOUT));427 expandStatusBar();428 }429 LOGGER.debug("Page source [expand status bar]: ".concat(getDriver().getPageSource()));430 Screenshot.captureByRule(getDriver(), "Clear notification - screenshot. Status bar should be opened. Attempt: " + i);431 try {432 notificationPage.clearNotifications();433 } catch (Exception e) {434 LOGGER.info("Exception during notification extraction.");435 }436 }437 collapseStatusBar();438 }439 /**440 * isStatusBarExpanded441 *442 * @return boolean443 */444 public boolean isStatusBarExpanded() {445 NotificationPage notificationPage = new NotificationPage(getDriver());446 return notificationPage.isStatusBarExpanded();447 }448 // End of Notification section449 // Fake GPS section450 /**451 * startFakeGPS to emulate GPS location452 *453 * @param location String - existing city (for ex. New York)454 * @return boolean return true if everything is ok.455 */456 public boolean setFakeGPSLocation(String location) {457 return setFakeGPSLocation(location, false);458 }459 /**460 * startFakeGPS to emulate GPS location461 *462 * @param location String - existing city (for ex. New York)463 * @param restartApk - if true restartDriver(true);464 * @return boolean return true if everything is ok.465 */466 public boolean setFakeGPSLocation(String location, boolean restartApk) {467 getDriver();468 boolean res = false;469 installApk(FAKE_GPS_APP_PATH, true);470 String activity = FAKE_GPS_APP_ACTIVITY;471 try {472 forceFakeGPSApkOpen();473 FakeGpsPage fakeGpsPage = new FakeGpsPage(getDriver());474 if (!fakeGpsPage.isOpened(1)) {475 LOGGER.error("Fake GPS application should be open but wasn't. Force opening.");476 openApp(activity);477 CommonUtils.pause(2);478 }479 res = fakeGpsPage.locationSearch(location);480 if (res) {481 LOGGER.info("Set Fake GPS locale: " + location);482 hideKeyboard();483 fakeGpsPage.clickSetLocation();484 }485 res = true;486 if (restartApk)487 restartDriver(true);488 } catch (Exception e) {489 LOGGER.error("Exception: ", e);490 }491 return res;492 }493 /**494 * stopFakeGPS stop using Fake GPS495 *496 * @return boolean497 */498 public boolean stopFakeGPS() {499 return stopFakeGPS(false);500 }501 /**502 * stopFakeGPS stop using Fake GPS503 *504 * @param restartApk - if true restartDriver(true);505 * @return boolean506 */507 public boolean stopFakeGPS(boolean restartApk) {508 getDriver();509 boolean res = false;510 String activity = FAKE_GPS_APP_ACTIVITY;511 try {512 forceFakeGPSApkOpen();513 FakeGpsPage fakeGpsPage = new FakeGpsPage(getDriver());514 if (!fakeGpsPage.isOpened(1)) {515 LOGGER.error("Fake GPS application should be open but wasn't. Force opening.");516 openApp(activity);517 CommonUtils.pause(2);518 }519 LOGGER.info("STOP Fake GPS locale");520 res = fakeGpsPage.clickStopFakeGps();521 if (restartApk)522 restartDriver(true);523 } catch (Exception e) {524 LOGGER.error("Exception: ", e);525 }526 LOGGER.info("Stop Fake GPS button was clicked: " + res);527 return res;528 }529 /**530 * forceFakeGPSApkOpen531 *532 * @return boolean533 */534 private boolean forceFakeGPSApkOpen() {535 return forceApkOpen(FAKE_GPS_APP_ACTIVITY, FAKE_GPS_APP_PACKAGE, FAKE_GPS_APP_PATH);536 }537 /**538 * forceApkOpen539 *540 * @param activity String541 * @param packageName String542 * @param apkPath String543 * @return boolean544 */545 private boolean forceApkOpen(String activity, String packageName, String apkPath) {546 boolean res;547 int attemps = 3;548 boolean isApkOpened = isAppRunning(packageName);549 while (!isApkOpened && attemps > 0) {550 LOGGER.info("Apk was not open. Attempt to open...");551 openApp(activity);552 CommonUtils.pause(2);553 isApkOpened = isAppRunning(packageName);554 attemps--;555 }556 if (!isApkOpened) {557 LOGGER.info("Probably APK was not installed correctly. Try to reinstall.");558 installApk(apkPath, true);559 openApp(activity);560 CommonUtils.pause(2);561 }562 if (isAppRunning(packageName)) {563 LOGGER.info("On '" + packageName + "' apk page");564 res = true;565 } else {566 LOGGER.error("Not on '" + packageName + "' page after all tries. Please check logs.");567 res = false;568 }569 return res;570 }571 // End of Fake GPS section572 // TimeZone change section573 /**574 * switchDeviceAutoTimeAndTimeZone575 *576 * @param autoSwitch boolean. If true - auto Time and TimeZone will be set577 * as On.578 */579 public void switchDeviceAutoTimeAndTimeZone(boolean autoSwitch) {580 String value = "0";581 if (autoSwitch) {582 value = "1";583 }584 executeAdbCommand("shell settings put global auto_time " + value);585 executeAdbCommand("shell settings put global auto_time_zone " + value);586 }587 /**588 * get Device Time Zone589 *590 * @return DeviceTimeZone591 */592 public DeviceTimeZone getDeviceTimeZone() {593 return getDeviceTimeZone("");594 }595 /**596 * get Device Time Zone. Set default TimeZone597 *598 * @param defaultTZ - default string.599 * @return DeviceTimeZone600 */601 public DeviceTimeZone getDeviceTimeZone(String defaultTZ) {602 getDriver(); // start driver in before class to assign it for particular603 // thread604 DeviceTimeZone dt = new DeviceTimeZone();605 String value = executeAdbCommand("shell settings get global auto_time");606 if (value.contains("0")) {607 dt.setAutoTime(false);608 } else {609 dt.setAutoTime(true);610 }611 value = executeAdbCommand("shell settings get global auto_time_zone");612 if (value.contains("0")) {613 dt.setAutoTimezone(false);614 } else {615 dt.setAutoTimezone(true);616 }617 value = executeAdbCommand("shell settings get system time_12_24");618 if (value.contains("12")) {619 dt.setTimeFormat(TimeFormat.FORMAT_12);620 } else {621 dt.setTimeFormat(TimeFormat.FORMAT_24);622 }623 if (defaultTZ.isEmpty()) {624 value = executeAdbCommand("shell getprop persist.sys.timezone");625 if (!value.isEmpty()) {626 dt.setTimezone(value);627 }628 } else {629 dt.setTimezone(defaultTZ);630 }631 value = executeAdbCommand("shell date -s %mynow%");632 LOGGER.info(value);633 if (!value.isEmpty()) {634 value = convertDateInCorrectString(parseOutputDate(value));635 dt.setSetDeviceDateTime(value);636 LOGGER.info(value);637 }638 dt.setChangeDateTime(false);639 dt.setRefreshDeviceTime(true);640 LOGGER.info(dt.toString());641 return dt;642 }643 /**644 * get Device Actual TimeZone645 *646 * @return String647 */648 public String getDeviceActualTimeZone() {649 String value = executeAdbCommand("shell getprop persist.sys.timezone");650 if (!value.isEmpty()) {651 LOGGER.info(value);652 }653 return value;654 }655 // Start of TimeZone Setting section656 /**657 * set Device TimeZone by using Apk658 *659 * @param timeZone String required timeZone in Android standard format660 * (Europe/London)661 * @param timeFormat String 12 or 24662 * @return boolean663 */664 public boolean setDeviceTimeZone(String timeZone, TimeFormat timeFormat) {665 return setDeviceTimeZone(timeZone, "", timeFormat, "", ChangeTimeZoneWorkflow.APK);666 }667 /**668 * set Device TimeZone using all supported workflows. By ADB, Settings and669 * Apk670 *671 * @param timeZone String required timeZone672 * @param timeFormat String 12 or 24673 * @param settingsTZ TimeFormat674 * @return boolean675 */676 public boolean setDeviceTimeZone(String timeZone, String settingsTZ, TimeFormat timeFormat) {677 return setDeviceTimeZone(timeZone, settingsTZ, timeFormat, "", ChangeTimeZoneWorkflow.ALL);678 }679 /**680 * set Device TimeZone. By required workflow: ADB, Settings or APK681 *682 * @param timeZone String required timeZone683 * @param timeFormat String 12 or 24684 * @param gmtStamp String685 * @param settingsTZ TimeFormat686 * @param workflow ChangeTimeZoneWorkflow687 * @return boolean688 */689 public boolean setDeviceTimeZone(String timeZone, String settingsTZ, TimeFormat timeFormat, String gmtStamp, ChangeTimeZoneWorkflow workflow) {690 boolean changed = false;691 getDriver(); // start driver in before class to assign it for particular692 // thread693 String actualTZ = getDeviceActualTimeZone();694 if (isRequiredTimeZone(actualTZ, timeZone)) {695 LOGGER.info("Required TimeZone is already set.");696 return true;697 }698 String currentAndroidVersion = IDriverPool.getDefaultDevice().getOsVersion();699 LOGGER.info("currentAndroidVersion=" + currentAndroidVersion);700 if (currentAndroidVersion.contains("7.") ||701 (IDriverPool.getDefaultDevice().getDeviceType() == DeviceType.Type.ANDROID_TABLET && !currentAndroidVersion.contains("8."))) {702 LOGGER.info("TimeZone changing for Android 7+ and tablets works only by TimeZone changer apk.");703 workflow = ChangeTimeZoneWorkflow.APK;704 }705 // Solution for ADB timezone changing.706 if (ChangeTimeZoneWorkflow.ADB.isSupported(workflow)) {707 LOGGER.info("Try to change TimeZone by ADB");708 LOGGER.info(setDeviceTimeZoneByADB(timeZone, timeFormat, ""));709 changed = applyTZChanges(ChangeTimeZoneWorkflow.ADB, timeZone);710 }711 // Solution for timezone changing by device Settings. (Tested on S7,712 // Note 3, S6, S5).713 if (!changed && ChangeTimeZoneWorkflow.SETTINGS.isSupported(workflow)) {714 LOGGER.info("Try to change TimeZone by Device Settings");715 setDeviceTimeZoneBySetting(timeZone, settingsTZ, timeFormat, gmtStamp);716 changed = applyTZChanges(ChangeTimeZoneWorkflow.SETTINGS, timeZone);717 }718 // Solution for using TimeZone Changer apk.719 if (!changed && ChangeTimeZoneWorkflow.APK.isSupported(workflow)) {720 LOGGER.info("Try to change TimeZone by TimeZone Changer apk.");721 setDeviceTimeZoneByChangerApk(timeZone, timeFormat);722 changed = applyTZChanges(ChangeTimeZoneWorkflow.APK, timeZone);723 }724 return changed;725 }726 // End of TimeZone change sections727 /**728 * Open camera on device729 */730 public void openCamera() {731 LOGGER.info("Camera will be opened");732 executeAdbCommand("shell am start -a android.media.action.IMAGE_CAPTURE");733 }734 /**735 * Android camera should be already opened736 */737 public void takePhoto() {738 LOGGER.info("Will take photo");739 executeAdbCommand("shell input keyevent KEYCODE_CAMERA");740 }741 // Private section742 // TimeZone Private methods743 /**744 * setDeviceTimeZoneByADB745 *746 * @param timeZone String747 * @param timeFormat TimeFormat748 * @param deviceSetDate String in format yyyyMMdd.HHmmss. Can be empty.749 * @return String750 */751 private String setDeviceTimeZoneByADB(String timeZone, TimeFormat timeFormat, String deviceSetDate) {752 boolean changeDateTime = true;753 String tzGMT = "";754 if (deviceSetDate.isEmpty()) {755 changeDateTime = false;756 }757 DeviceTimeZone dt = new DeviceTimeZone(false, false, timeFormat, timeZone, tzGMT, deviceSetDate, changeDateTime, true);758 return setDeviceTimeZoneByADB(dt);759 }760 /**761 * setDeviceTimeZoneByADB Automatic date and time = OFF (settings - date and762 * time) adb shell settings put global auto_time 0 Automatic time zone = OFF763 * (settings - date and time) adb shell settings put global auto_time_zone 0764 * <p>765 * Set Time Zone on device adb shell setprop persist.sys.timezone766 * "America/Chicago"767 * <p>768 * Check timezones: <a href=769 * "https://en.wikipedia.org/wiki/List_of_tz_database_time_zones">List_of_tz_database_time_zones</a>770 * <p>771 * Check time on device adb shell date -s %mynow%772 * <p>773 * Restart application774 *775 * @param dt DeviceTimeZone776 * @return String actual Device Date and Time777 */778 private String setDeviceTimeZoneByADB(DeviceTimeZone dt) {779 if (dt == null) {780 LOGGER.error("DeviceTimeZone is not initialised.");781 dt = new DeviceTimeZone();782 }783 LOGGER.info(dt.toString());784 String autoTime = "0";785 String autoTimeZone = "0";786 if (dt.isAutoTime()) {787 autoTime = "1";788 }789 executeAdbCommand("shell settings put global auto_time " + autoTime);790 if (dt.isAutoTimezone()) {791 autoTimeZone = "1";792 }793 executeAdbCommand("shell settings put global auto_time_zone " + autoTimeZone);794 setSystemTime(dt.getTimeFormat());795 if (!dt.getTimezone().isEmpty()) {796 executeAdbCommand("shell setprop persist.sys.timezone \"" + dt.getTimezone() + "\"");797 }798 if (dt.isRefreshDeviceTime()) {799 executeAdbCommand("shell am broadcast -a android.intent.action.TIME_SET");800 }801 if (dt.isChangeDateTime() && !dt.getSetDeviceDateTime().isEmpty()) {802 // Try to set date for device but it will not work on not rooted803 // devices804 executeAdbCommand("shell date " + dt.getSetDeviceDateTime());805 }806 String actualDT = executeAdbCommand("shell date -s %mynow%");807 LOGGER.info(actualDT);808 return actualDT;809 }810 /**811 * setDeviceTimeZoneBySetting812 *813 * @param timeZone String814 * @param settingsTZ String815 * @param timeFormat TimeFormat816 * @param gmtStamp String817 */818 private void setDeviceTimeZoneBySetting(String timeZone, String settingsTZ, TimeFormat timeFormat, String gmtStamp) {819 String actualTZ = getDeviceActualTimeZone();820 // String tz = DeviceTimeZone.getTimezoneOffset(timeZone);821 if (isRequiredTimeZone(actualTZ, timeZone)) {822 LOGGER.info("Required timeZone is already set.");823 return;824 }825 try {826 openDateTimeSettingsSetupWizard(true, timeFormat);827 String res = getCurrentDeviceFocus();828 if (res.contains(".Settings$DateTimeSettingsActivity")) {829 LOGGER.info("On '.Settings$DateTimeSettingsActivity' page");830 } else {831 LOGGER.error("Not on '.Settings$DateTimeSettingsActivity' page");832 }833 DateTimeSettingsPage dtSettingsPage = new DateTimeSettingsPage(getDriver());834 if (!dtSettingsPage.isOpened()) {835 openDateTimeSettingsSetupWizard(true, timeFormat);836 }837 if (dtSettingsPage.isOpened()) {838 LOGGER.info("Date Time Settings page was open.");839 } else {840 LOGGER.error("Date Time Settings page should be open.");841 }842 dtSettingsPage.openTimeZoneSetting();843 dtSettingsPage.selectTimeZone(timeZone, settingsTZ, gmtStamp);844 dtSettingsPage.clickNextButton();845 } catch (Exception e) {846 LOGGER.error("Exception: ", e);847 }848 }849 /**850 * setDeviceTimeZoneByChangerApk851 *852 * @param timeZone String853 * @param timeFormat TimeFormat854 */855 private void setDeviceTimeZoneByChangerApk(String timeZone, TimeFormat timeFormat) {856 String actualTZ = getDeviceActualTimeZone();857 String tz = DeviceTimeZone.getTimezoneOffset(timeZone);858 LOGGER.info("Required TimeZone offset: " + tz);859 if (isRequiredTimeZone(actualTZ, timeZone)) {860 LOGGER.info("Required timeZone is already set.");861 return;862 }863 installApk(TZ_CHANGE_APP_PATH, true);864 try {865 forceTZChangingApkOpen(true, timeFormat);866 TZChangerPage tzChangerPage = new TZChangerPage(getDriver());867 if (tzChangerPage.isOpened(3)) {868 LOGGER.info("TimeZone changer main page was open.");869 } else {870 LOGGER.error("TimeZone changer main page should be open. Retry to open.");871 openTZChangingApk(true, timeFormat);872 }873 tzChangerPage.selectTimeZone(timeZone);874 } catch (Exception e) {875 LOGGER.error("Exception: ", e);876 }877 }878 private boolean applyTZChanges(ChangeTimeZoneWorkflow workflow, String expectedZone) {879 boolean res = false;880 String actualTZ = getDeviceActualTimeZone();881 if (isRequiredTimeZone(actualTZ, expectedZone)) {882 LOGGER.info("Required timeZone '" + expectedZone + "' was set by " + workflow.toString() + ". Restarting driver to apply changes.");883 restartDriver(true);884 res = true;885 } else {886 LOGGER.error("TimeZone was not changed by " + workflow.toString() + ". Actual TZ is: " + actualTZ);887 }888 return res;889 }890 /**891 * comparingExpectedAndActualTZ892 *893 * @param actualTZ String894 * @param expextedTZ String895 * @return boolean896 */897 private boolean isRequiredTimeZone(String actualTZ, String expextedTZ) {898 boolean res = actualTZ.equals(expextedTZ);899 if (!res) {900 String[] actTZ = actualTZ.split("/");901 String lastActTZ = actTZ[actTZ.length - 1];902 String[] timeZoneTZ = expextedTZ.split("/");903 String lastTimeZoneTZ = timeZoneTZ[timeZoneTZ.length - 1];904 LOGGER.debug("Comparing '" + lastActTZ + "' with '" + lastTimeZoneTZ + "'.");905 res = lastActTZ.equals(lastTimeZoneTZ);906 }907 return res;908 }909 /**910 * @param turnOffAuto boolean911 * @param timeFormat TimeFormat912 * @return boolean913 */914 private boolean forceTZChangingApkOpen(boolean turnOffAuto, TimeFormat timeFormat) {915 boolean res = false;916 String tzPackageName = TZ_CHANGE_APP_PACKAGE;917 int attemps = 3;918 boolean isTzOpened = isAppRunning(tzPackageName);919 while (!isTzOpened && attemps > 0) {920 LOGGER.info("TimeZoneChanger apk was not open. Attempt to open...");921 openTZChangingApk(turnOffAuto, timeFormat);922 isTzOpened = isAppRunning(tzPackageName);923 attemps--;924 }925 if (!isTzOpened) {926 LOGGER.info("Probably TimeZone Changer APK was not installed correctly. Try to reinstall.");927 installApk(TZ_CHANGE_APP_PATH, true);928 openTZChangingApk(turnOffAuto, timeFormat);929 }930 TZChangerPage tzChangerPage = new TZChangerPage(getDriver());931 if (!tzChangerPage.isOpened(10)) {932 openTZChangingApk(turnOffAuto, timeFormat);933 }934 if (tzChangerPage.isOpened(3)) {935 LOGGER.info("TimeZone changer main page was open.");936 res = true;937 } else {938 LOGGER.error("TimeZone changer main page should be open.");939 openTZChangingApk(turnOffAuto, timeFormat);940 res = false;941 }942 if (isAppRunning(tzPackageName)) {943 LOGGER.info("On TZ changer apk page");944 res = true;945 } else {946 LOGGER.error("Not on com.futurek.android.tzc page after all tries. Please check logs.");947 res = false;948 }949 return res;950 }951 /**952 * openDateTimeSettingsSetupWizard in settings953 *954 * @param turnOffAuto - turn off AutoTimeZone and AutoTime955 * @param timeFormat - can be 12 or 24. Or empty.956 */957 private void openDateTimeSettingsSetupWizard(boolean turnOffAuto, TimeFormat timeFormat) {958 if (turnOffAuto) {959 switchDeviceAutoTimeAndTimeZone(false);960 }961 setSystemTime(timeFormat);962 openApp("com.android.settings/.Settings\\$DateTimeSettingsActivity");963 }964 /**965 * openDateTimeSettingsSetupWizard in settings966 *967 * @param turnOffAuto - turn off AutoTimeZone and AutoTime968 * @param timeFormat - can be 12 or 24. Or empty.969 */970 private void openTZChangingApk(boolean turnOffAuto, TimeFormat timeFormat) {971 if (turnOffAuto) {972 switchDeviceAutoTimeAndTimeZone(false);973 }974 setSystemTime(timeFormat);975 openApp(TZ_CHANGE_APP_ACTIVITY);976 CommonUtils.pause(2);977 }978 private void setSystemTime(TimeFormat timeFormat) {979 switch (timeFormat) {980 case FORMAT_12:981 LOGGER.info("Set 12 hours format");982 executeAdbCommand("shell settings put system time_12_24 12");983 break;984 case FORMAT_24:985 LOGGER.info("Set 24 hours format");986 executeAdbCommand("shell settings put system time_12_24 24");987 break;988 }989 }990 /**991 * Parse DateTime which came in format 'EE MMM dd hh:mm:ss zz yyyy'992 *993 * @param inputDate String994 * @return Date995 */996 private Date parseOutputDate(String inputDate) {997 Date result = new Date();998 try {999 LOGGER.info("Input date: " + inputDate);1000 SimpleDateFormat inDateFormat = new SimpleDateFormat("EE MMM dd hh:mm:ss zz yyyy");...

Full Screen

Full Screen

executeAdbCommand

Using AI Code Generation

copy

Full Screen

1package com.qaprosoft.carina.core.foundation.utils.android;2import java.io.BufferedReader;3import java.io.IOException;4import java.io.InputStreamReader;5import org.apache.log4j.Logger;6import com.qaprosoft.carina.core.foundation.utils.Configuration;7import com.qaprosoft.carina.core.foundation.utils.Configuration.Parameter;8public class AndroidUtils implements IAndroidUtils {9 private static final Logger LOGGER = Logger.getLogger(AndroidUtils.class);10 public String executeAdbCommand(String command) {11 String adb = Configuration.get(Parameter.ANDROID_ADB_PATH);12 String serial = Configuration.get(Parameter.ANDROID_SERIAL);13 String cmd = adb + " -s " + serial + " " + command;14 LOGGER.info("Executing adb command: " + cmd);15 StringBuilder output = new StringBuilder();16 Process p;17 try {18 p = Runtime.getRuntime().exec(cmd);19 p.waitFor();20 BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));21 String line = "";22 while ((line = reader.readLine()) != null) {23 output.append(line + "24");25 }26 } catch (IOException | InterruptedException e) {27 LOGGER.error("Failed to execute adb command!", e);28 }29 return output.toString();30 }31}32package com.qaprosoft.carina.core.foundation.utils.android;33import org.testng.Assert;34import org.testng.annotations.Test;35public class AndroidUtilsTest {36 public void testExecuteAdbCommand() {37 AndroidUtils androidUtils = new AndroidUtils();38 String command = "shell dumpsys battery";39 String output = androidUtils.executeAdbCommand(command);40 Assert.assertTrue(output.contains("level"));41 }42}43package com.qaprosoft.carina.core.foundation.utils.android;44import org.testng.Assert;45import org.testng.annotations.Test;46public class AndroidUtilsTest {47 public void testExecuteAdbCommand() {48 AndroidUtils androidUtils = new AndroidUtils();49 String command = "shell dumpsys battery";50 String output = androidUtils.executeAdbCommand(command);51 Assert.assertTrue(output.contains("level"));52 }53}

Full Screen

Full Screen

executeAdbCommand

Using AI Code Generation

copy

Full Screen

1import com.qaprosoft.carina.core.foundation.utils.android.IAndroidUtils;2IAndroidUtils androidUtils = new IAndroidUtils();3androidUtils.executeAdbCommand("adb devices");4import com.qaprosoft.carina.core.foundation.utils.android.AndroidUtils;5AndroidUtils androidUtils = new AndroidUtils();6androidUtils.executeAdbCommand("adb devices");7import com.qaprosoft.carina.core.foundation.utils.android.AdbUtils;8AdbUtils adbUtils = new AdbUtils();9adbUtils.executeAdbCommand("adb devices");10import com.qaprosoft.carina.core.foundation.utils.android.AdbExecutor;11AdbExecutor adbExecutor = new AdbExecutor();12adbExecutor.executeAdbCommand("adb devices");13import com.qaprosoft.carina.core.foundation.utils.android.AdbExecutor;14AdbExecutor adbExecutor = new AdbExecutor();15adbExecutor.executeAdbCommand("adb devices");16import com.qaprosoft.carina.core.foundation.utils.android.AdbExecutor;17AdbExecutor adbExecutor = new AdbExecutor();18adbExecutor.executeAdbCommand("adb devices");19import com.qaprosoft.carina.core.foundation.utils.android.AdbExecutor;20AdbExecutor adbExecutor = new AdbExecutor();21adbExecutor.executeAdbCommand("adb devices");22import com.qaprosoft.carina.core.foundation.utils.android.AdbExecutor;23AdbExecutor adbExecutor = new AdbExecutor();24adbExecutor.executeAdbCommand("adb devices");25import com.qaprosoft.carina.core.foundation.utils.android.AdbExecutor

Full Screen

Full Screen

executeAdbCommand

Using AI Code Generation

copy

Full Screen

1executeAdbCommand("adb shell am start -a android.settings.SETTINGS");2executeAdbCommand("adb shell am start -a android.settings.SETTINGS");3executeAdbCommand("adb shell am start -a android.settings.SETTINGS");4executeAdbCommand("adb shell am start -a android.settings.SETTINGS");5executeAdbCommand("adb shell am start -a android.settings.SETTINGS");6executeAdbCommand("adb shell am start -a android.settings.SETTINGS");7executeAdbCommand("adb shell am start -a android.settings.SETTINGS");8executeAdbCommand("adb shell am start -a android.settings.SETTINGS");9executeAdbCommand("adb shell am start -a android.settings.SETTINGS");10executeAdbCommand("adb shell am start -a android.settings.SETTINGS");11executeAdbCommand("adb shell am start -a android.settings.SETTINGS");12executeAdbCommand("adb shell am start -a android.settings.SETTINGS");

Full Screen

Full Screen

executeAdbCommand

Using AI Code Generation

copy

Full Screen

1String command = "adb devices";2String result = AndroidUtils.executeAdbCommand(command);3String command = "adb devices";4String result = AndroidUtils.executeAdbCommand(command);5String command = "adb devices";6String result = AndroidUtils.executeAdbCommand(command);7String command = "adb devices";8String result = AndroidUtils.executeAdbCommand(command);9String command = "adb devices";10String result = AndroidUtils.executeAdbCommand(command);11String command = "adb devices";12String result = AndroidUtils.executeAdbCommand(command);13String command = "adb devices";14String result = AndroidUtils.executeAdbCommand(command);15String command = "adb devices";16String result = AndroidUtils.executeAdbCommand(command);17String command = "adb devices";18String result = AndroidUtils.executeAdbCommand(command);19String command = "adb devices";20String result = AndroidUtils.executeAdbCommand(command);

Full Screen

Full Screen

executeAdbCommand

Using AI Code Generation

copy

Full Screen

1package com.qaprosoft.carina.core.foundation.utils.android;2import com.qaprosoft.carina.core.foundation.utils.Configuration;3import com.qaprosoft.carina.core.foundation.utils.ios.IOSUtils;4import com.qaprosoft.carina.core.foundation.utils.mobile.MobileUtils;5import com.qaprosoft.carina.core.foundation.utils.ownership.MethodOwner;6import java.io.IOException;7import java.util.ArrayList;8import java.util.List;9public class AndroidUtils implements IAndroidUtils {10 private static final Logger LOGGER = Logger.getLogger(AndroidUtils.class);11 @MethodOwner(owner = "qpsdemo")12 public static void executeAdbCommand(String command) {13 try {14 Runtime.getRuntime().exec(command);15 } catch (IOException e) {16 LOGGER.error("Failed to execute adb command!", e);17 }18 }19 @MethodOwner(owner = "qpsdemo")20 public static void executeAdbCommand(String command, String device) {21 try {22 Runtime.getRuntime().exec(command);23 } catch (IOException e) {24 LOGGER.error("Failed to execute adb command on device " + device, e);25 }26 }27 @MethodOwner(owner = "qpsdemo")28 public static void executeAdbCommand(String command, String device, String appPackage) {29 try {30 Runtime.getRuntime().exec(command);31 } catch (IOException e) {32 LOGGER.error("Failed to execute adb command on device " + device + " for app " + appPackage, e);33 }34 }35 @MethodOwner(owner = "qpsdemo")36 public static void executeAdbCommand(String command, String device, String appPackage, String appActivity) {37 try {38 Runtime.getRuntime().exec(command);39 } catch (IOException e) {40 LOGGER.error("Failed to execute adb command on device " + device + " for app " + appPackage + " and activity " + appActivity, e);41 }42 }43 @MethodOwner(owner = "qpsdemo")44 public static void executeAdbCommand(String command, String device, String appPackage, String appActivity, String appWaitActivity) {45 try {46 Runtime.getRuntime().exec(command);47 } catch (IOException e) {48 LOGGER.error("Failed to execute adb command on device " + device + " for app " + appPackage + " and activity " + appActivity + " and wait activity " + appWaitActivity,

Full Screen

Full Screen

executeAdbCommand

Using AI Code Generation

copy

Full Screen

1import com.qaprosoft.carina.core.foundation.utils.android.IAndroidUtils;2import com.qaprosoft.carina.core.foundation.utils.android.AndroidUtils;3import com.qaprosoft.carina.core.foundation.utils.android.AdbUtils;4public class AdbCommandTest {5public static void main(String[] args) {6IAndroidUtils adb = new AdbUtils();7adb.executeAdbCommand("adb shell input keyevent 3");8}9}10import com.qaprosoft.carina.core.foundation.utils.android.IAndroidUtils;11import com.qaprosoft.carina.core.foundation.utils.android.AndroidUtils;12import com.qaprosoft.carina.core.foundation.utils.android.AdbUtils;13IAndroidUtils adb = new AdbUtils();14IAndroidUtils adb = new AdbUtils();15import com.qaprosoft.carina.core.foundation.utils.android.AdbUtils;16public class AdbCommandTest {17public static void main(String[] args) {18AdbUtils adb = new AdbUtils();19adb.executeAdbCommand("adb shell input keyevent 3");20}21}

Full Screen

Full Screen

executeAdbCommand

Using AI Code Generation

copy

Full Screen

1public class 1 {2 public static void main(String[] args) {3 IAndroidUtils androidUtils = new AndroidUtils();4 androidUtils.executeAdbCommand(adbCommand);5 }6}7public class 2 {8 public static void main(String[] args) {9 AndroidUtils.executeAdbCommand(adbCommand);10 }11}12public class 3 {13 public static void main(String[] args) {14 IAndroidUtils androidUtils = new AndroidUtils();15 androidUtils.executeAdbCommand(adbCommand);16 }17}18public class 4 {19 public static void main(String[] args) {20 IAndroidUtils.executeAdbCommand(adbCommand);21 }22}23public class 5 {24 public static void main(String[] args) {25 IAndroidUtils.executeAdbCommand(adbCommand);26 }27}28public class 6 {29 public static void main(String[] args) {

Full Screen

Full Screen

executeAdbCommand

Using AI Code Generation

copy

Full Screen

1public class 1 {2 public static void main(String[] args) {3 String deviceId = "emulator-5554";4 String imeiNumber = IAndroidUtils.executeAdbCommand(deviceId, "shell service call iphonesubinfo 1");5 System.out.println(imeiNumber);6 }7}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful