How to use withTimeout method of io.appium.java_client.android.appmanagement.AndroidTerminateApplicationOptions class

Best io.appium code snippet using io.appium.java_client.android.appmanagement.AndroidTerminateApplicationOptions.withTimeout

AndroidStepHandler.java

Source:AndroidStepHandler.java Github

copy

Full Screen

...153 if (androidDriver != null) {154 //终止测试包155 if (!testPackage.equals("")) {156 try {157 androidDriver.terminateApp(testPackage, new AndroidTerminateApplicationOptions().withTimeout(Duration.ofMillis(1000)));158 } catch (Exception e) {159 e.printStackTrace();160 }161 }162 androidDriver.quit();163 log.sendStepLog(StepType.PASS, "退出连接设备", "");164 }165 } catch (Exception e) {166 log.sendStepLog(StepType.WARN, "测试终止异常!请检查设备连接状态", "");167 //测试异常168 setResultDetailStatus(ResultDetailStatus.WARN);169 e.printStackTrace();170 }171 }172 public void waitDevice(int waitCount) {173 log.sendStepLog(StepType.INFO, "设备非空闲状态!第" + waitCount + "次等待连接...", "");174 }175 public void waitDeviceTimeOut() {176 log.sendStepLog(StepType.ERROR, "等待设备超时!测试跳过!", "");177 //测试标记为异常178 setResultDetailStatus(ResultDetailStatus.WARN);179 }180 public String getUdId() {181 return udId;182 }183 public AndroidDriver getAndroidDriver() {184 return androidDriver;185 }186 /**187 * @param status188 * @return void189 * @author ZhouYiXun190 * @des 设置测试状态191 * @date 2021/8/16 23:46192 */193 public void setResultDetailStatus(int status) {194 if (status > this.status) {195 this.status = status;196 }197 }198 public void sendStatus() {199 log.sendStatusLog(status);200 }201 //判断有无出错202 public int getStatus() {203 return status;204 }205 //调试每次重设状态206 public void resetResultDetailStatus() {207 status = 1;208 }209 /**210 * @return boolean211 * @author ZhouYiXun212 * @des 检测是否低电量213 * @date 2021/8/16 23:16214 */215 public boolean getBattery() {216 double battery = androidDriver.getBatteryInfo().getLevel();217 if (battery <= 0.1) {218 log.sendStepLog(StepType.ERROR, "设备电量过低!", "跳过本次测试...");219 return true;220 } else {221 return false;222 }223 }224 /**225 * @return void226 * @author ZhouYiXun227 * @des 获取性能信息(Appium自带的cpu和network方法貌似有bug, 后续再优化)228 * @date 2021/8/16 23:16229 */230 public void getPerform() {231 if (!testPackage.equals("")) {232 List<String> performanceData = Arrays.asList("memoryinfo", "batteryinfo");233 for (String performName : performanceData) {234 List<List<Object>> re = androidDriver.getPerformanceData(testPackage, performName, 1);235 List<Integer> mem;236 if (performName.equals("memoryinfo")) {237 mem = Arrays.asList(0, 1, 2, 5, 6, 7);238 } else {239 mem = Collections.singletonList(0);240 }241 JSONObject perform = new JSONObject();242 for (Integer memNum : mem) {243 perform.put(re.get(0).get(memNum).toString(), re.get(1).get(memNum));244 }245 log.sendPerLog(testPackage, performName.equals("memoryinfo") ? 1 : 2, perform);246 }247 }248 }249 //配合前端渲染,需要每个节点加上id250 private int xpathId = 1;251 /**252 * @return com.alibaba.fastjson.JSONArray253 * @author ZhouYiXun254 * @des 获取页面xpath信息255 * @date 2021/8/16 23:16256 */257 public JSONArray getResource() {258 androidDriver.context("NATIVE_APP");259 JSONArray elementList = new JSONArray();260 Document doc = Jsoup.parse(androidDriver.getPageSource());261 String xpath = "/hierarchy";262 elementList.addAll(getChildren(doc.body().children().get(0).children(), xpath));263 xpathId = 1;264 return elementList;265 }266 /**267 * @param elements268 * @param xpath 父级节点xpath269 * @return com.alibaba.fastjson.JSONArray270 * @author ZhouYiXun271 * @des 获取子节点信息272 * @date 2021/8/16 23:36273 */274 public JSONArray getChildren(org.jsoup.select.Elements elements, String xpath) {275 JSONArray elementList = new JSONArray();276 for (int i = 0; i < elements.size(); i++) {277 JSONObject ele = new JSONObject();278 //tag次数279 int tagCount = 0;280 //兄弟节点index281 int siblingIndex = 0;282 String indexXpath;283 for (int j = 0; j < elements.size(); j++) {284 if (elements.get(j).attr("class").equals(elements.get(i).attr("class"))) {285 tagCount++;286 }287 //当i==j时候,兄弟节点index等于tag出现次数,因为xpath多个tag的时候,[]里面下标是从1开始288 if (i == j) {289 siblingIndex = tagCount;290 }291 }292 //如果tag出现次数等于1,xpath结尾不添加[]293 if (tagCount == 1) {294 indexXpath = xpath + "/" + elements.get(i).attr("class");295 } else {296 indexXpath = xpath + "/" + elements.get(i).attr("class") + "[" + siblingIndex + "]";297 }298 ele.put("id", xpathId);299 xpathId++;300 ele.put("label", "<" + elements.get(i).attr("class") + ">");301 JSONObject detail = new JSONObject();302 detail.put("xpath", indexXpath);303 for (Attribute attr : elements.get(i).attributes()) {304 //把bounds字段拆出来解析,方便前端进行截取305 if (attr.getKey().equals("bounds")) {306 String bounds = attr.getValue().replace("][", ":");307 String pointStart = bounds.substring(1, bounds.indexOf(":"));308 String pointEnd = bounds.substring(bounds.indexOf(":") + 1, bounds.indexOf("]"));309 detail.put("bStart", pointStart);310 detail.put("bEnd", pointEnd);311 }312 detail.put(attr.getKey(), attr.getValue());313 }314 ele.put("detail", detail);315 if (elements.get(i).children().size() > 0) {316 ele.put("children", getChildren(elements.get(i).children(), indexXpath));317 }318 elementList.add(ele);319 }320 return elementList;321 }322 /**323 * @return void324 * @author ZhouYiXun325 * @des 开始录像326 * @date 2021/8/16 23:56327 */328 public void startRecord() {329 try {330 AndroidStartScreenRecordingOptions recordOption = new AndroidStartScreenRecordingOptions();331 //限制30分钟,appium支持的最长时间332 recordOption.withTimeLimit(Duration.ofMinutes(30));333 //开启bugReport,开启后录像会有相关附加信息334 recordOption.enableBugReport();335 //是否强制终止上次录像并开始新的录像336 recordOption.enableForcedRestart();337 //限制码率,防止录像过大338 recordOption.withBitRate(3000000);339 androidDriver.startRecordingScreen(recordOption);340 } catch (Exception e) {341 log.sendRecordLog(false, "", "");342 }343 }344 /**345 * @return void346 * @author ZhouYiXun347 * @des 停止录像348 * @date 2021/8/16 23:56349 */350 public void stopRecord() {351 File recordDir = new File("test-output/record");352 if (!recordDir.exists()) {353 recordDir.mkdirs();354 }355 long timeMillis = Calendar.getInstance().getTimeInMillis();356 String fileName = timeMillis + "_" + udId.substring(0, 4) + ".mp4";357 File uploadFile = new File(recordDir + File.separator + fileName);358 try {359 //加锁防止内存泄漏360 synchronized (AndroidStepHandler.class) {361 FileOutputStream fileOutputStream = new FileOutputStream(uploadFile);362 byte[] bytes = Base64Utils.decodeFromString((androidDriver.stopRecordingScreen()));363 fileOutputStream.write(bytes);364 fileOutputStream.close();365 }366 log.sendRecordLog(true, fileName, UploadTools.uploadPatchRecord(uploadFile));367 } catch (Exception e) {368 log.sendRecordLog(false, fileName, "");369 }370 }371// public void settingSonicPlugins(IDevice iDevice) {372// try {373// androidDriver.activateApp("com.sonic.plugins");374// try {375// Thread.sleep(1000);376// } catch (Exception e) {377// }378// log.sendStepLog(StepType.INFO, "已安装Sonic插件!", "");379// } catch (Exception e) {380// log.sendStepLog(StepType.ERROR, "未安装Sonic插件!", "");381// throw e;382// }383// try {384// if (!androidDriver.currentActivity().equals("com.sonic.plugins.MainActivity")) {385// try {386// AndroidDeviceBridgeTool.executeCommand(iDevice, "input keyevent 4");387// Thread.sleep(1000);388// } catch (Exception e) {389// }390// }391// findEle("xpath", "//android.widget.TextView[@text='服务状态:已开启']");392// } catch (Exception e) {393// log.sendStepLog(StepType.ERROR, "未开启Sonic插件服务!请到辅助功能或无障碍开启", "");394// throw e;395// }396// try {397// findEle("id", "com.sonic.plugins:id/password_edit").clear();398// if (AndroidPasswordMap.getMap().get(log.udId) != null399// && (AndroidPasswordMap.getMap().get(log.udId) != null)400// && (!AndroidPasswordMap.getMap().get(log.udId).equals(""))) {401// findEle("id", "com.sonic.plugins:id/password_edit").sendKeys(AndroidPasswordMap.getMap().get(log.udId));402// } else {403// findEle("id", "com.sonic.plugins:id/password_edit").sendKeys("sonic123456");404// }405// findEle("id", "com.sonic.plugins:id/save").click();406// } catch (Exception e) {407// log.sendStepLog(StepType.ERROR, "配置Sonic插件服务失败!", "");408// throw e;409// }410// }411 public void install(HandleDes handleDes, String path) {412 handleDes.setStepDes("安装应用");413 handleDes.setDetail("App安装路径: " + path);414// IDevice iDevice = AndroidDeviceBridgeTool.getIDeviceByUdId(log.udId);415// String manufacturer = iDevice.getProperty(IDevice.PROP_DEVICE_MANUFACTURER);416 try {417 androidDriver.unlockDevice();418 if (androidDriver.getConnection().isAirplaneModeEnabled()) {419 androidDriver.toggleAirplaneMode();420 }421 if (!androidDriver.getConnection().isWiFiEnabled()) {422 androidDriver.toggleWifi();423 }424 } catch (Exception e) {425 log.sendStepLog(StepType.WARN, "安装前准备跳过...", "");426 }427 log.sendStepLog(StepType.INFO, "", "开始安装App,请稍后...");428// if (manufacturer.equals("OPPO") || manufacturer.equals("vivo") || manufacturer.equals("Meizu")) {429// settingSonicPlugins(iDevice);430// AndroidDeviceBridgeTool.executeCommand(iDevice, "input keyevent 3");431// }432// //单独适配一下oppo433// if (manufacturer.equals("OPPO")) {434// try {435// androidDriver.installApp(path, new AndroidInstallApplicationOptions()436// .withAllowTestPackagesEnabled().withReplaceEnabled()437// .withGrantPermissionsEnabled().withTimeout(Duration.ofMillis(60000)));438// } catch (Exception e) {439// }440// //单独再适配colorOs441// if (androidDriver.currentActivity().equals(".verification.login.AccountActivity")) {442// try {443// if (AndroidPasswordMap.getMap().get(log.udId) != null444// && (AndroidPasswordMap.getMap().get(log.udId) != null)445// && (!AndroidPasswordMap.getMap().get(log.udId).equals(""))) {446// findEle("id", "com.coloros.safecenter:id/et_login_passwd_edit"447// ).sendKeys(AndroidPasswordMap.getMap().get(log.udId));448// } else {449// findEle("id", "com.coloros.safecenter:id/et_login_passwd_edit"450// ).sendKeys("sonic123456");451// }452// findEle("id", "android:id/button1").click();453// } catch (Exception e) {454// }455// }456// AtomicInteger tryTime = new AtomicInteger(0);457// AndroidDeviceThreadPool.cachedThreadPool.execute(() -> {458// while (tryTime.get() < 20) {459// tryTime.getAndIncrement();460// //部分oppo有继续安装461// try {462// WebElement getContinueButton = findEle("id", "com.android.packageinstaller:id/virus_scan_panel");463// Thread.sleep(2000);464// AndroidDeviceBridgeTool.executeCommand(iDevice,465// String.format("input tap %d %d", (getContinueButton.getRect().width) / 2466// , getContinueButton.getRect().y + getContinueButton.getRect().height));467// Thread.sleep(2000);468// } catch (Exception e) {469// e.printStackTrace();470// }471// //低版本oppo安装按钮在右边472// try {473// findEle("id", "com.android.packageinstaller:id/install_confirm_panel");474// WebElement getInstallButton = findEle("id", "com.android.packageinstaller:id/bottom_button_layout");475// Thread.sleep(2000);476// AndroidDeviceBridgeTool.executeCommand(iDevice, String.format("input tap %d %d"477// , ((getInstallButton.getRect().width) / 4) * 3478// , getInstallButton.getRect().y + (getInstallButton.getRect().height) / 2));479// Thread.sleep(2000);480// } catch (Exception e) {481// e.printStackTrace();482// }483// //部分oppo无法点击484// try {485// findEle("xpath", "//*[@text='应用权限']");486// WebElement getInstallButton = findEle("id", "com.android.packageinstaller:id/install_confirm_panel");487// Thread.sleep(2000);488// AndroidDeviceBridgeTool.executeCommand(iDevice, String.format("input tap %d %d"489// , (getInstallButton.getRect().width) / 2, getInstallButton.getRect().y + getInstallButton.getRect().height));490// Thread.sleep(2000);491// } catch (Exception e) {492// e.printStackTrace();493// }494// if (!androidDriver.getCurrentPackage().equals("com.android.packageinstaller")) {495// break;496// }497// }498// });499// while (androidDriver.getCurrentPackage().equals("com.android.packageinstaller") && tryTime.get() < 20) {500// try {501// findEle("xpath", "//*[@text='完成']").click();502// } catch (Exception e) {503// }504// }505// } else {506 try {507 androidDriver.installApp(path, new AndroidInstallApplicationOptions()508 .withAllowTestPackagesEnabled().withReplaceEnabled()509 .withGrantPermissionsEnabled().withTimeout(Duration.ofMillis(600000)));510 } catch (Exception e) {511 handleDes.setE(e);512 return;513 }514// }515 }516 public void uninstall(HandleDes handleDes, String appPackage) {517 handleDes.setStepDes("卸载应用");518 handleDes.setDetail("App包名: " + appPackage);519 try {520 androidDriver.removeApp(appPackage);521 } catch (Exception e) {522 handleDes.setE(e);523 }524 }525 /**526 * @param packageName527 * @return void528 * @author ZhouYiXun529 * @des 终止app530 * @date 2021/8/16 23:46531 */532 public void terminate(HandleDes handleDes, String packageName) {533 handleDes.setStepDes("终止应用");534 handleDes.setDetail("应用包名: " + packageName);535 try {536 androidDriver.terminateApp(packageName, new AndroidTerminateApplicationOptions().withTimeout(Duration.ofMillis(1000)));537 } catch (Exception e) {538 handleDes.setE(e);539 }540 }541 public void runBackground(HandleDes handleDes, long time) {542 handleDes.setStepDes("后台运行应用");543 handleDes.setDetail("后台运行App " + time + " ms");544 try {545 androidDriver.runAppInBackground(Duration.ofMillis(time));546 } catch (Exception e) {547 handleDes.setE(e);548 }549 }550 public void openApp(HandleDes handleDes, String appPackage) {551 handleDes.setStepDes("打开应用");552 handleDes.setDetail("App包名: " + appPackage);553 try {554 testPackage = appPackage;555 androidDriver.activateApp(appPackage);556 } catch (Exception e) {557 handleDes.setE(e);558 }559 }560 public void rotateDevice(HandleDes handleDes, String text) {561 try {562 String s = "";563 switch (text) {564 case "screenSub":565 s = "sub";566 handleDes.setStepDes("左转屏幕");567 break;568 case "screenAdd":569 s = "add";570 handleDes.setStepDes("右转屏幕");571 break;572 case "screenAbort":573 s = "abort";574 handleDes.setStepDes("关闭自动旋转");575 break;576 }577 AndroidDeviceBridgeTool.screen(AndroidDeviceBridgeTool.getIDeviceByUdId(udId), s);578 } catch (Exception e) {579 handleDes.setE(e);580 }581 }582 public void lock(HandleDes handleDes) {583 handleDes.setStepDes("锁定屏幕");584 try {585 androidDriver.lockDevice();586 } catch (Exception e) {587 handleDes.setE(e);588 }589 }590 public void unLock(HandleDes handleDes) {591 handleDes.setStepDes("解锁屏幕");592 try {593 androidDriver.unlockDevice();594 } catch (Exception e) {595 handleDes.setE(e);596 }597 }598 public void airPlaneMode(HandleDes handleDes) {599 handleDes.setStepDes("切换飞行模式");600 try {601 androidDriver.toggleAirplaneMode();602 } catch (Exception e) {603 handleDes.setE(e);604 }605 }606 public void wifiMode(HandleDes handleDes) {607 handleDes.setStepDes("打开WIFI网络");608 try {609 if (!androidDriver.getConnection().isWiFiEnabled()) {610 androidDriver.toggleWifi();611 }612 } catch (Exception e) {613 handleDes.setE(e);614 }615 }616 public void locationMode(HandleDes handleDes) {617 handleDes.setStepDes("切换位置服务");618 try {619 androidDriver.toggleLocationServices();620 } catch (Exception e) {621 handleDes.setE(e);622 }623 }624 public void asserts(HandleDes handleDes, String actual, String expect, String type) {625 handleDes.setDetail("真实值: " + actual + " 期望值: " + expect);626 try {627 switch (type) {628 case "assertEquals":629 handleDes.setStepDes("断言验证(相等)");630 assertEquals(actual, expect);631 break;632 case "assertTrue":633 handleDes.setStepDes("断言验证(包含)");634 assertTrue(actual.contains(expect));635 break;636 case "assertNotTrue":637 handleDes.setStepDes("断言验证(不包含)");638 assertFalse(actual.contains(expect));639 break;640 }641 } catch (AssertionError e) {642 handleDes.setE(e);643 }644 }645 public String getText(HandleDes handleDes, String des, String selector, String pathValue) {646 String s = "";647 handleDes.setStepDes("获取" + des + "文本");648 handleDes.setDetail("获取" + selector + ":" + pathValue + "文本");649 try {650 s = findEle(selector, pathValue).getText();651 log.sendStepLog(StepType.INFO, "", "文本获取结果: " + s);652 } catch (Exception e) {653 handleDes.setE(e);654 }655 return s;656 }657 public void hideKey(HandleDes handleDes) {658 handleDes.setStepDes("隐藏键盘");659 handleDes.setDetail("隐藏弹出键盘");660 try {661 androidDriver.hideKeyboard();662 } catch (Exception e) {663 handleDes.setE(e);664 }665 }666 public void toWebView(HandleDes handleDes, String webViewName) {667 handleDes.setStepDes("切换到" + webViewName);668 try {669 androidDriver.context(webViewName);670 } catch (Exception e) {671 handleDes.setE(e);672 }673 }674 public void click(HandleDes handleDes, String des, String selector, String pathValue) {675 handleDes.setStepDes("点击" + des);676 handleDes.setDetail("点击" + selector + ": " + pathValue);677 try {678 findEle(selector, pathValue).click();679 } catch (Exception e) {680 handleDes.setE(e);681 }682 }683 public void sendKeys(HandleDes handleDes, String des, String selector, String pathValue, String keys) {684 if (keys.contains("{{random}}")) {685 String random = (int) (Math.random() * 10 + Math.random() * 10 * 2) + 5 + "";686 keys = keys.replace("{{random}}", random);687 }688 if (keys.contains("{{timestamp}}")) {689 String timeMillis = Calendar.getInstance().getTimeInMillis() + "";690 keys = keys.replace("{{timestamp}}", timeMillis);691 }692 keys = replaceTrans(keys);693 handleDes.setStepDes("对" + des + "输入内容");694 handleDes.setDetail("对" + selector + ": " + pathValue + " 输入: " + keys);695 try {696 findEle(selector, pathValue).sendKeys(keys);697 } catch (Exception e) {698 handleDes.setE(e);699 }700 }701 public void getTextAndAssert(HandleDes handleDes, String des, String selector, String pathValue, String expect) {702 handleDes.setStepDes("获取" + des + "文本");703 handleDes.setDetail("获取" + selector + ":" + pathValue + "文本");704 try {705 String s = findEle(selector, pathValue).getText();706 log.sendStepLog(StepType.INFO, "", "文本获取结果: " + s);707 try {708 expect = replaceTrans(expect);709 assertEquals(s, expect);710 log.sendStepLog(StepType.INFO, "验证文本", "真实值: " + s + " 期望值: " + expect);711 } catch (AssertionError e) {712 log.sendStepLog(StepType.ERROR, "验证" + des + "文本失败!", "");713 handleDes.setE(e);714 }715 } catch (Exception e) {716 handleDes.setE(e);717 }718 }719 public void longPressPoint(HandleDes handleDes, String des, String xy, int time) {720 int x = Integer.parseInt(xy.substring(0, xy.indexOf(",")));721 int y = Integer.parseInt(xy.substring(xy.indexOf(",") + 1));722 handleDes.setStepDes("长按" + des);723 handleDes.setDetail("长按坐标" + time + "毫秒 (" + x + "," + y + ")");724 try {725 TouchAction ta = new TouchAction(androidDriver);726 ta.longPress(PointOption.point(x, y)).waitAction(WaitOptions.waitOptions(Duration.ofMillis(time))).release().perform();727 } catch (Exception e) {728 handleDes.setE(e);729 }730 }731 public void keyCode(HandleDes handleDes, String key) {732 handleDes.setStepDes("按系统按键" + key + "键");733 try {734 androidDriver.pressKey(new KeyEvent().withKey(AndroidKey.valueOf(key)));735 } catch (Exception e) {736 handleDes.setE(e);737 }738 }739 public void multiAction(HandleDes handleDes, String des1, String xy1, String des2, String xy2, String des3, String xy3, String des4, String xy4) {740 int x1 = Integer.parseInt(xy1.substring(0, xy1.indexOf(",")));741 int y1 = Integer.parseInt(xy1.substring(xy1.indexOf(",") + 1));742 int x2 = Integer.parseInt(xy2.substring(0, xy2.indexOf(",")));743 int y2 = Integer.parseInt(xy2.substring(xy2.indexOf(",") + 1));744 int x3 = Integer.parseInt(xy3.substring(0, xy3.indexOf(",")));745 int y3 = Integer.parseInt(xy3.substring(xy3.indexOf(",") + 1));746 int x4 = Integer.parseInt(xy4.substring(0, xy4.indexOf(",")));747 int y4 = Integer.parseInt(xy4.substring(xy4.indexOf(",") + 1));748 String detail = "坐标" + des1 + "( " + x1 + ", " + y1 + " )移动到坐标" + des2 + "( " + x2 + ", " + y2 + " ),同时坐标" + des3 + "( " + x3 + ", " + y3 + " )移动到坐标" + des4 + "( " + x4 + ", " + y4 + " )";749 handleDes.setStepDes("双指操作");750 handleDes.setDetail(detail);751 try {752 TouchAction hand1 = new TouchAction(androidDriver);753 TouchAction hand2 = new TouchAction(androidDriver);754 MultiTouchAction multiTouchAction = new MultiTouchAction(androidDriver);755 hand1.press(PointOption.point(x1, y1)).moveTo(PointOption.point(x2, y2)).release();756 hand2.press(PointOption.point(x3, y3)).moveTo(PointOption.point(x4, y4)).release();757 multiTouchAction.add(hand1);758 multiTouchAction.add(hand2);759 multiTouchAction.perform();760 } catch (Exception e) {761 handleDes.setE(e);762 }763 }764 public void tap(HandleDes handleDes, String des, String xy) {765 int x = Integer.parseInt(xy.substring(0, xy.indexOf(",")));766 int y = Integer.parseInt(xy.substring(xy.indexOf(",") + 1));767 handleDes.setStepDes("点击" + des);768 handleDes.setDetail("点击坐标(" + x + "," + y + ")");769 try {770 TouchAction ta = new TouchAction(androidDriver);771 ta.tap(PointOption.point(x, y)).perform();772 } catch (Exception e) {773 handleDes.setE(e);774 }775 }776 public void swipePoint(HandleDes handleDes, String des1, String xy1, String des2, String xy2) {777 int x1 = Integer.parseInt(xy1.substring(0, xy1.indexOf(",")));778 int y1 = Integer.parseInt(xy1.substring(xy1.indexOf(",") + 1));779 int x2 = Integer.parseInt(xy2.substring(0, xy2.indexOf(",")));780 int y2 = Integer.parseInt(xy2.substring(xy2.indexOf(",") + 1));781 handleDes.setStepDes("滑动拖拽" + des1 + "到" + des2);782 handleDes.setDetail("拖动坐标(" + x1 + "," + y1 + ")到(" + x2 + "," + y2 + ")");783 try {784 TouchAction ta = new TouchAction(androidDriver);785 ta.press(PointOption.point(x1, y1)).waitAction(WaitOptions.waitOptions(Duration.ofMillis(300))).moveTo(PointOption.point(x2, y2)).release().perform();786 } catch (Exception e) {787 handleDes.setE(e);788 }789 }790 public void swipe(HandleDes handleDes, String des, String selector, String pathValue, String des2, String selector2, String pathValue2) {791 WebElement webElement = findEle(selector, pathValue);792 WebElement webElement2 = findEle(selector2, pathValue2);793 int x1 = webElement.getLocation().getX();794 int y1 = webElement.getLocation().getY();795 int x2 = webElement2.getLocation().getX();796 int y2 = webElement2.getLocation().getY();797 handleDes.setStepDes("滑动拖拽" + des + "到" + des2);798 handleDes.setDetail("拖动坐标(" + x1 + "," + y1 + ")到(" + x2 + "," + y2 + ")");799 try {800 TouchAction ta = new TouchAction(androidDriver);801 ta.press(PointOption.point(x1, y1)).waitAction(WaitOptions.waitOptions(Duration.ofMillis(300))).moveTo(PointOption.point(x2, y2)).release().perform();802 } catch (Exception e) {803 handleDes.setE(e);804 }805 }806 public void longPress(HandleDes handleDes, String des, String selector, String pathValue, int time) {807 handleDes.setStepDes("长按" + des);808 handleDes.setDetail("长按控件元素" + time + "毫秒 ");809 try {810 TouchAction ta = new TouchAction(androidDriver);811 WebElement webElement = findEle(selector, pathValue);812 int x = webElement.getLocation().getX();813 int y = webElement.getLocation().getY();814 Duration duration = Duration.ofMillis(time);815 ta.longPress(PointOption.point(x, y)).waitAction(WaitOptions.waitOptions(duration)).release().perform();816 } catch (Exception e) {817 handleDes.setE(e);818 }819 }820 public void clear(HandleDes handleDes, String des, String selector, String pathValue) {821 handleDes.setStepDes("清空" + des);822 handleDes.setDetail("清空" + selector + ": " + pathValue);823 try {824 findEle(selector, pathValue).clear();825 } catch (Exception e) {826 handleDes.setE(e);827 }828 }829 public void getTitle(HandleDes handleDes, String expect) {830 String title = androidDriver.getTitle();831 handleDes.setStepDes("验证网页标题");832 handleDes.setDetail("标题:" + title + ",期望值:" + expect);833 try {834 assertEquals(title, expect);835 } catch (AssertionError e) {836 handleDes.setE(e);837 }838 }839 public void clickByImg(HandleDes handleDes, String des, String pathValue) throws Exception {840 handleDes.setStepDes("点击图片" + des);841 handleDes.setDetail(pathValue);842 File file = null;843 if (pathValue.startsWith("http")) {844 try {845 file = DownImageTool.download(pathValue);846 } catch (Exception e) {847 handleDes.setE(e);848 return;849 }850 }851 FindResult findResult = null;852 try {853 SIFTFinder siftFinder = new SIFTFinder();854 findResult = siftFinder.getSIFTFindResult(file, getScreenToLocal());855 } catch (Exception e) {856 log.sendStepLog(StepType.WARN, "SIFT图像算法出错,切换算法中...",857 "");858 }859 if (findResult != null) {860 log.sendStepLog(StepType.INFO, "图片定位到坐标:(" + findResult.getX() + "," + findResult.getY() + ") 耗时:" + findResult.getTime() + " ms",861 findResult.getUrl());862 } else {863 log.sendStepLog(StepType.INFO, "SIFT算法无法定位图片,切换AKAZE算法中...",864 "");865 try {866 AKAZEFinder akazeFinder = new AKAZEFinder();867 findResult = akazeFinder.getAKAZEFindResult(file, getScreenToLocal());868 } catch (Exception e) {869 log.sendStepLog(StepType.WARN, "AKAZE图像算法出错,切换模版匹配算法中...",870 "");871 }872 if (findResult != null) {873 log.sendStepLog(StepType.INFO, "图片定位到坐标:(" + findResult.getX() + "," + findResult.getY() + ") 耗时:" + findResult.getTime() + " ms",874 findResult.getUrl());875 } else {876 log.sendStepLog(StepType.INFO, "AKAZE算法无法定位图片,切换模版匹配算法中...",877 "");878 try {879 TemMatcher temMatcher = new TemMatcher();880 findResult = temMatcher.getTemMatchResult(file, getScreenToLocal());881 } catch (Exception e) {882 log.sendStepLog(StepType.WARN, "模版匹配算法出错",883 "");884 }885 if (findResult != null) {886 log.sendStepLog(StepType.INFO, "图片定位到坐标:(" + findResult.getX() + "," + findResult.getY() + ") 耗时:" + findResult.getTime() + " ms",887 findResult.getUrl());888 } else {889 handleDes.setE(new Exception("图片定位失败!"));890 }891 }892 }893 if (findResult != null) {894 try {895 TouchAction ta = new TouchAction(androidDriver);896 ta.tap(PointOption.point(findResult.getX(), findResult.getY())).perform();897 } catch (Exception e) {898 log.sendStepLog(StepType.ERROR, "点击" + des + "失败!", "");899 handleDes.setE(e);900 }901 }902 }903 public void readText(HandleDes handleDes, String language, String text) throws Exception {904// TextReader textReader = new TextReader();905// String result = textReader.getTessResult(getScreenToLocal(), language);906// log.sendStepLog(StepType.INFO, "",907// "图像文字识别结果:<br>" + result);908// String filter = result.replaceAll(" ", "");909 handleDes.setStepDes("图像文字识别");910 handleDes.setDetail("(该功能暂时关闭)期望包含文本:" + text);911// if (!filter.contains(text)) {912// handleDes.setE(new Exception("图像文字识别不通过!"));913// }914 }915 public void toHandle(HandleDes handleDes, String titleName) throws Exception {916 handleDes.setStepDes("切换Handle");917 Thread.sleep(1000);918 Set<String> handle = androidDriver.getWindowHandles();//获取handles919 String ha;920 for (int i = 1; i <= handle.size(); i++) {921 ha = (String) handle.toArray()[handle.size() - i];//查找handle922 try {923 androidDriver.switchTo().window(ha);//切换到最后一个handle924 } catch (Exception e) {925 }926 if (androidDriver.getTitle().equals(titleName)) {927 handleDes.setDetail("切换到Handle:" + ha);928 log.sendStepLog(StepType.INFO, "页面标题:" + androidDriver.getTitle(), "");929 break;930 }931 }932 }933 public File getScreenToLocal() {934 File file = ((TakesScreenshot) androidDriver).getScreenshotAs(OutputType.FILE);935 File resultFile = new File("test-output/" + log.udId + Calendar.getInstance().getTimeInMillis() + ".jpg");936 try {937 FileCopyUtils.copy(file, resultFile);938 } catch (IOException e) {939 e.printStackTrace();940 }941 return resultFile;942 }943 public String replaceTrans(String text) {944 if (text.contains("{{") && text.contains("}}")) {945 String tail = text.substring(text.indexOf("{{") + 2);946 if (tail.contains("}}")) {947 String child = tail.substring(tail.indexOf("}}") + 2);948 String middle = tail.substring(0, tail.indexOf("}}"));949 text = text.substring(0, text.indexOf("}}") + 2);950 if (globalParams.getString(middle) != null) {951 text = text.replace("{{" + middle + "}}", globalParams.getString(middle));952 }953 text = text + replaceTrans(child);954 }955 }956 return text;957 }958 public void checkImage(HandleDes handleDes, String des, String pathValue, double matchThreshold) throws Exception {959 try {960 log.sendStepLog(StepType.INFO, "开始检测" + des + "兼容", "检测与当前设备截图相似度,期望相似度为" + matchThreshold + "%");961 File file = null;962 if (pathValue.startsWith("http")) {963 file = DownImageTool.download(pathValue);964 }965 double score = SimilarityChecker.getSimilarMSSIMScore(file, getScreenToLocal(), true);966 handleDes.setStepDes("检测" + des + "图片相似度");967 handleDes.setDetail("相似度为" + score * 100 + "%");968 if (score == 0) {969 handleDes.setE(new Exception("图片相似度检测不通过!比对图片分辨率不一致!"));970 } else if (score < (matchThreshold / 100)) {971 handleDes.setE(new Exception("图片相似度检测不通过!expect " + matchThreshold + " but " + score * 100));972 }973 } catch (Exception e) {974 handleDes.setE(e);975 }976 }977 public void exceptionLog(Throwable e) {978 log.sendStepLog(StepType.WARN, "", "异常信息: " + e.fillInStackTrace().toString());979 }980 public void errorScreen() {981 try {982 androidDriver.context("NATIVE_APP");//先切换回app983 log.sendStepLog(StepType.WARN, "获取异常截图", UploadTools984 .upload(((TakesScreenshot) androidDriver).getScreenshotAs(OutputType.FILE), "imageFiles"));985 } catch (Exception e) {986 log.sendStepLog(StepType.ERROR, "捕获截图失败", "");987 }988 }989 public String stepScreen(HandleDes handleDes) {990 handleDes.setStepDes("获取截图");991 String url = "";992 try {993 androidDriver.context("NATIVE_APP");//先切换回app994 url = UploadTools.upload(((TakesScreenshot) androidDriver)995 .getScreenshotAs(OutputType.FILE), "imageFiles");996 handleDes.setDetail(url);997 } catch (Exception e) {998 handleDes.setE(e);999 }1000 return url;1001 }1002 public Set<String> getWebView() {1003 Set<String> contextNames = androidDriver.getContextHandles();1004 return contextNames;1005 }1006 public String getCurrentActivity() {1007 return androidDriver.currentActivity();1008 }1009 public void pause(HandleDes handleDes, int time) {1010 handleDes.setStepDes("强制等待");1011 handleDes.setDetail("等待" + time + " ms");1012 try {1013 Thread.sleep(time);1014 } catch (InterruptedException e) {1015 handleDes.setE(e);1016 }1017 }1018 public void runMonkey(HandleDes handleDes, JSONObject content, List<JSONObject> text) {1019 handleDes.setStepDes("运行随机事件测试完毕");1020 String packageName = content.getString("packageName");1021 int pctNum = content.getInteger("pctNum");1022 if (!androidDriver.isAppInstalled(packageName)) {1023 log.sendStepLog(StepType.ERROR, "应用未安装!", "设备未安装 " + packageName);1024 handleDes.setE(new Exception("未安装应用"));1025 return;1026 }1027 IDevice iDevice = AndroidDeviceBridgeTool.getIDeviceByUdId(udId);1028 JSONArray options = content.getJSONArray("options");1029 int width = androidDriver.manage().window().getSize().width;1030 int height = androidDriver.manage().window().getSize().height;1031 int sleepTime = 50;1032 int systemEvent = 0;1033 int tapEvent = 0;1034 int longPressEvent = 0;1035 int swipeEvent = 0;1036 int zoomEvent = 0;1037 int navEvent = 0;1038 boolean isOpenH5Listener = false;1039 boolean isOpenPackageListener = false;1040 boolean isOpenActivityListener = false;1041 boolean isOpenNetworkListener = false;1042 if (!options.isEmpty()) {1043 for (int i = options.size() - 1; i >= 0; i--) {1044 JSONObject jsonOption = (JSONObject) options.get(i);1045 if (jsonOption.getString("name").equals("sleepTime")) {1046 sleepTime = jsonOption.getInteger("value");1047 }1048 if (jsonOption.getString("name").equals("systemEvent")) {1049 systemEvent = jsonOption.getInteger("value");1050 }1051 if (jsonOption.getString("name").equals("tapEvent")) {1052 tapEvent = jsonOption.getInteger("value");1053 }1054 if (jsonOption.getString("name").equals("longPressEvent")) {1055 longPressEvent = jsonOption.getInteger("value");1056 }1057 if (jsonOption.getString("name").equals("swipeEvent")) {1058 swipeEvent = jsonOption.getInteger("value");1059 }1060 if (jsonOption.getString("name").equals("zoomEvent")) {1061 zoomEvent = jsonOption.getInteger("value");1062 }1063 if (jsonOption.getString("name").equals("navEvent")) {1064 navEvent = jsonOption.getInteger("value");1065 }1066 if (jsonOption.getString("name").equals("isOpenH5Listener")) {1067 isOpenH5Listener = jsonOption.getBoolean("value");1068 }1069 if (jsonOption.getString("name").equals("isOpenPackageListener")) {1070 isOpenPackageListener = jsonOption.getBoolean("value");1071 }1072 if (jsonOption.getString("name").equals("isOpenActivityListener")) {1073 isOpenActivityListener = jsonOption.getBoolean("value");1074 }1075 if (jsonOption.getString("name").equals("isOpenNetworkListener")) {1076 isOpenNetworkListener = jsonOption.getBoolean("value");1077 }1078 options.remove(options.get(i));1079 }1080 }1081 int finalSleepTime = sleepTime;1082 int finalTapEvent = tapEvent;1083 int finalLongPressEvent = longPressEvent;1084 int finalSwipeEvent = swipeEvent;1085 int finalZoomEvent = zoomEvent;1086 int finalSystemEvent = systemEvent;1087 int finalNavEvent = navEvent;1088 Future<?> randomThread = AndroidDeviceThreadPool.cachedThreadPool.submit(() -> {1089 log.sendStepLog(StepType.INFO, "", "随机事件数:" + pctNum +1090 "<br>目标应用:" + packageName1091 + "<br>用户操作时延:" + finalSleepTime + " ms"1092 + "<br>轻触事件权重:" + finalTapEvent1093 + "<br>长按事件权重:" + finalLongPressEvent1094 + "<br>滑动事件权重:" + finalSwipeEvent1095 + "<br>多点触控事件权重:" + finalZoomEvent1096 + "<br>物理按键事件权重:" + finalSystemEvent1097 + "<br>系统事件权重:" + finalNavEvent1098 );1099 openApp(new HandleDes(), packageName);1100 TouchAction ta = new TouchAction(androidDriver);1101 TouchAction ta2 = new TouchAction(androidDriver);1102 MultiTouchAction multiTouchAction = new MultiTouchAction(androidDriver);1103 int totalCount = finalSystemEvent + finalTapEvent + finalLongPressEvent + finalSwipeEvent + finalZoomEvent + finalNavEvent;1104 for (int i = 0; i < pctNum; i++) {1105 try {1106 int random = new Random().nextInt(totalCount);1107 if (random >= 0 && random < finalSystemEvent) {1108 int key = new Random().nextInt(9);1109 String keyType = "";1110 switch (key) {1111 case 0:1112 keyType = "HOME";1113 break;1114 case 1:1115 keyType = "BACK";1116 break;1117 case 2:1118 keyType = "MENU";1119 break;1120 case 3:1121 keyType = "APP_SWITCH";1122 break;1123 case 4:1124 keyType = "BRIGHTNESS_DOWN";1125 break;1126 case 5:1127 keyType = "BRIGHTNESS_UP";1128 break;1129 case 6:1130 keyType = "VOLUME_UP";1131 break;1132 case 7:1133 keyType = "VOLUME_DOWN";1134 break;1135 case 8:1136 keyType = "VOLUME_MUTE";1137 break;1138 }1139 androidDriver.pressKey(new KeyEvent(AndroidKey.valueOf(keyType)));1140 }1141 if (random >= finalSystemEvent && random < (finalSystemEvent + finalTapEvent)) {1142 int x = new Random().nextInt(width - 60) + 60;1143 int y = new Random().nextInt(height - 60) + 60;1144 ta.tap(PointOption.point(x, y)).perform();1145 }1146 if (random >= (finalSystemEvent + finalTapEvent) && random < (finalSystemEvent + finalTapEvent + finalLongPressEvent)) {1147 int x = new Random().nextInt(width - 60) + 60;1148 int y = new Random().nextInt(height - 60) + 60;1149 ta.longPress(PointOption.point(x, y)).waitAction(WaitOptions.waitOptions(Duration.ofSeconds(new Random().nextInt(3) + 1))).release().perform();1150 }1151 if (random >= (finalSystemEvent + finalTapEvent + finalLongPressEvent) && random < (finalSystemEvent + finalTapEvent + finalLongPressEvent + finalSwipeEvent)) {1152 int x1 = new Random().nextInt(width - 60) + 60;1153 int y1 = new Random().nextInt(height - 80) + 80;1154 int x2 = new Random().nextInt(width - 60) + 60;1155 int y2 = new Random().nextInt(height - 80) + 80;1156 ta.press(PointOption.point(x1, y1)).waitAction(WaitOptions.waitOptions(Duration.ofMillis(200))).moveTo(PointOption.point(x2, y2)).release().perform();1157 }1158 if (random >= (finalSystemEvent + finalTapEvent + finalLongPressEvent + finalSwipeEvent) && random < (finalSystemEvent + finalTapEvent + finalLongPressEvent + finalSwipeEvent + finalZoomEvent)) {1159 int x1 = new Random().nextInt(width - 80);1160 int y1 = new Random().nextInt(height - 80);1161 int x2 = new Random().nextInt(width - 100);1162 int y2 = new Random().nextInt(height - 80);1163 int x3 = new Random().nextInt(width - 100);1164 int y3 = new Random().nextInt(height - 80);1165 int x4 = new Random().nextInt(width - 100);1166 int y4 = new Random().nextInt(height - 80);1167 ta.press(PointOption.point(x1, y1)).waitAction(WaitOptions.waitOptions(Duration.ofMillis(200))).moveTo(PointOption.point(x2, y2)).release();1168 ta2.press(PointOption.point(x3, y3)).waitAction(WaitOptions.waitOptions(Duration.ofMillis(200))).moveTo(PointOption.point(x4, y4)).release();1169 multiTouchAction.add(ta);1170 multiTouchAction.add(ta2);1171 multiTouchAction.perform();1172 }1173 if (random >= (finalSystemEvent + finalTapEvent + finalLongPressEvent + finalSwipeEvent + finalZoomEvent) && random < (finalSystemEvent + finalTapEvent + finalLongPressEvent + finalSwipeEvent + finalZoomEvent + finalNavEvent)) {1174 androidDriver.toggleWifi();1175 }1176 Thread.sleep(finalSleepTime);1177 } catch (Throwable e) {1178 e.printStackTrace();1179 }1180 }1181 }1182 );1183 Boolean finalIsOpenH5Listener = isOpenH5Listener;1184 Future<?> H5Listener = AndroidDeviceThreadPool.cachedThreadPool.submit(() -> {1185 if (finalIsOpenH5Listener) {1186 int h5Time = 0;1187 while (!randomThread.isDone()) {1188 try {1189 Thread.sleep(8000);1190 } catch (InterruptedException e) {1191 e.printStackTrace();1192 }1193 try {1194 if (androidDriver.findElementsByClassName("android.webkit.WebView").size() > 0) {1195 h5Time++;1196 AndroidDeviceBridgeTool.executeCommand(iDevice, "input keyevent 4");1197 } else {1198 h5Time = 0;1199 }1200 if (h5Time >= 12) {1201 androidDriver.terminateApp(packageName, new AndroidTerminateApplicationOptions().withTimeout(Duration.ofMillis(1000)));1202 h5Time = 0;1203 }1204 } catch (Throwable e) {1205 e.printStackTrace();1206 }1207 }1208 }1209 }1210 );1211 boolean finalIsOpenPackageListener = isOpenPackageListener;1212 Future<?> packageListener = AndroidDeviceThreadPool.cachedThreadPool.submit(() -> {1213 if (finalIsOpenPackageListener) {1214 while (!randomThread.isDone()) {1215 int waitTime = 0;1216 while (waitTime <= 10 && (!randomThread.isDone())) {1217 try {1218 Thread.sleep(5000);1219 } catch (InterruptedException e) {1220 e.printStackTrace();1221 }1222 if (!androidDriver.getCurrentPackage().equals(packageName)) {1223 androidDriver.activateApp(packageName);1224 }1225 waitTime++;1226 }1227 androidDriver.activateApp(packageName);1228 }1229 }1230 }1231 );1232 boolean finalIsOpenActivityListener = isOpenActivityListener;1233 Future<?> activityListener = AndroidDeviceThreadPool.cachedThreadPool.submit(() -> {1234 if (finalIsOpenActivityListener) {1235 if (text.isEmpty()) {1236 return;1237 }1238 Set<String> blackList = new HashSet<>();1239 for (JSONObject activities : text) {1240 blackList.add(activities.getString("name"));1241 }1242 while (!randomThread.isDone()) {1243 try {1244 Thread.sleep(8000);1245 } catch (InterruptedException e) {1246 e.printStackTrace();1247 }1248 if (blackList.contains(getCurrentActivity())) {1249 AndroidDeviceBridgeTool.executeCommand(iDevice, "input keyevent 4");1250 } else continue;1251 try {1252 Thread.sleep(8000);1253 } catch (InterruptedException e) {1254 e.printStackTrace();1255 }1256 if (blackList.contains(getCurrentActivity())) {1257 androidDriver.terminateApp(packageName, new AndroidTerminateApplicationOptions().withTimeout(Duration.ofMillis(1000)));1258 }1259 }1260 }1261 }1262 );1263 boolean finalIsOpenNetworkListener = isOpenNetworkListener;1264 Future<?> networkListener = AndroidDeviceThreadPool.cachedThreadPool.submit(() -> {1265 if (finalIsOpenNetworkListener) {1266 while (!randomThread.isDone()) {1267 try {1268 Thread.sleep(8000);1269 } catch (InterruptedException e) {1270 e.printStackTrace();1271 }...

Full Screen

Full Screen

IOSStepHandler.java

Source:IOSStepHandler.java Github

copy

Full Screen

...117 if (iosDriver != null) {118 //终止测试包119 if (!testPackage.equals("")) {120 try {121 iosDriver.terminateApp(testPackage, new AndroidTerminateApplicationOptions().withTimeout(Duration.ofMillis(1000)));122 } catch (Exception e) {123 e.printStackTrace();124 }125 }126 iosDriver.quit();127 log.sendStepLog(StepType.PASS, "退出连接设备", "");128 if (IOSProcessMap.getMap().get(udId) != null) {129 List<Process> processList = IOSProcessMap.getMap().get(udId);130 for (Process p : processList) {131 if (p != null) {132 p.children().forEach(ProcessHandle::destroy);133 p.destroy();134 }135 }...

Full Screen

Full Screen

AndroidTerminateApplicationOptions.java

Source:AndroidTerminateApplicationOptions.java Github

copy

Full Screen

...30 * @param timeout the actual timeout value. The minimum time resolution31 * unit is one millisecond.32 * @return self instance for chaining.33 */34 public AndroidTerminateApplicationOptions withTimeout(Duration timeout) {35 checkArgument(!checkNotNull(timeout).isNegative(), "The timeout value cannot be negative");36 this.timeout = timeout;37 return this;38 }39 @Override40 public Map<String, Object> build() {41 final ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();42 ofNullable(timeout).map(x -> builder.put("timeout", x.toMillis()));43 return builder.build();44 }45}...

Full Screen

Full Screen

AndInteractsWithApps.java

Source:AndInteractsWithApps.java Github

copy

Full Screen

...12 AppiumDriver driver = CreateDriverSession.initializeDriver("Android");13 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);14 By views = MobileBy.AccessibilityId("Views");15 driver.findElement(views).click();16 // driver.terminateApp("",new AndroidTerminateApplicationOptions().withTimeout());17 Thread.sleep(5000);18 // driver.runAppInBackground(Duration.ofMillis(5000));19 // driver.activateApp("",AndroidA);20 // System.out.println(driver.isAppInstalled(""));21 String appUrl = System.getProperty("user.dir") + File.separator + "src" +22 File.separator + "main" + File.separator +23 "resources" + File.separator + "ApiDemos-debug.apk";24 // driver.installApp(appUrl,new AndroidInstallApplicationOptions().withReplaceEnabled());25 System.out.println(driver.queryAppState("")); // to check the state of the application26 }27}...

Full Screen

Full Screen

withTimeout

Using AI Code Generation

copy

Full Screen

1package appium.java;2import java.net.MalformedURLException;3import java.net.URL;4import java.util.concurrent.TimeUnit;5import org.openqa.selenium.remote.DesiredCapabilities;6import io.appium.java_client.android.AndroidDriver;7import io.appium.java_client.android.appmanagement.AndroidTerminateApplicationOptions;8public class TerminateApplication {9 public static void main(String[] args) throws MalformedURLException {10 DesiredCapabilities cap = new DesiredCapabilities();11 cap.setCapability("deviceName", "Android Device");12 cap.setCapability("udid", "emulator-5554");13 cap.setCapability("platformName", "Android");14 cap.setCapability("platformVersion", "10.0");15 cap.setCapability("appPackage", "com.android.calculator2");16 cap.setCapability("appActivity", "com.android.calculator2.Calculator");17 cap.setCapability("noReset", "true");

Full Screen

Full Screen

withTimeout

Using AI Code Generation

copy

Full Screen

1package appium;2import java.net.MalformedURLException;3import java.net.URL;4import java.time.Duration;5import java.util.concurrent.TimeUnit;6import org.openqa.selenium.By;7import org.openqa.selenium.remote.DesiredCapabilities;8import io.appium.java_client.AppiumDriver;9import io.appium.java_client.MobileElement;10import io.appium.java_client.android.AndroidDriver;11import io.appium.java_client.android.appmanagement.AndroidTerminateApplicationOptions;12import io.appium.java_client.android.nativekey.AndroidKey;13import io.appium.java_client.android.nativekey.KeyEvent;14public class AppiumJavaTerminateApp {15 public static void main(String[] args) throws MalformedURLException, InterruptedException {16 DesiredCapabilities caps = new DesiredCapabilities();17 caps.setCapability("deviceName", "Android Emulator");18 caps.setCapability("platformName", "Android");19 caps.setCapability("appPackage", "com.android.calculator2");20 caps.setCapability("appActivity", "com.android.calculator2.Calculator");21 caps.setCapability("noReset", true);

Full Screen

Full Screen

withTimeout

Using AI Code Generation

copy

Full Screen

1AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();2options.withTimeout(Duration.ofSeconds(10));3driver.terminateApp("com.example.android.contactmanager", options);4AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();5options.withTimeout(Duration.ofSeconds(10));6driver.terminateApp("com.example.android.contactmanager", options);7const options = new AndroidTerminateApplicationOptions();8options.withTimeout(10);9await driver.terminateApp('com.example.android.contactmanager', options);10const options = new AndroidTerminateApplicationOptions();11options.withTimeout(10);12await driver.terminateApp('com.example.android.contactmanager', options);13options = AndroidTerminateApplicationOptions()14options.withTimeout(10)15self.driver.terminate_app('com.example.android.contactmanager', options)16options = AndroidTerminateApplicationOptions()17options.withTimeout(10)18self.driver.terminate_app('com.example.android.contactmanager', options)19options.withTimeout(10)20@driver.terminate_app('com.example.android.contactmanager', options)21options.withTimeout(10)22@driver.terminate_app('com.example.android.contactmanager', options)23options = AndroidTerminateApplicationOptions()24options.withTimeout(10)25self.driver.terminate_app('com.example.android.contactmanager', options)26options = AndroidTerminateApplicationOptions()27options.withTimeout(10)

Full Screen

Full Screen

withTimeout

Using AI Code Generation

copy

Full Screen

1AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();2options.withTimeout(Duration.ofSeconds(30));3driver.terminateApp("com.example.android.contactmanager", options);4AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();5options.withTimeout(Duration.ofSeconds(30));6driver.terminateApp("com.example.android.contactmanager", options);7AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();8options.withTimeout(Duration.ofSeconds(30));9driver.terminateApp("com.example.android.contactmanager", options);10AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();11options.withTimeout(Duration.ofSeconds(30));12driver.terminateApp("com.example.android.contactmanager", options);13AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();14options.withTimeout(Duration.ofSeconds(30));15driver.terminateApp("com.example.android.contactmanager", options);16AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();17options.withTimeout(Duration.ofSeconds(30));18driver.terminateApp("com.example.android.contactmanager", options);19AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();20options.withTimeout(Duration.ofSeconds(30));21driver.terminateApp("com.example.android.contactmanager", options);22AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();23options.withTimeout(Duration.ofSeconds(30));24driver.terminateApp("com.example.android.contactmanager", options);25AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();26options.withTimeout(Duration.ofSeconds(30));27driver.terminateApp("com.example.android.contactmanager

Full Screen

Full Screen

withTimeout

Using AI Code Generation

copy

Full Screen

1AndroidTerminateApplicationOptions terminateOptions = new AndroidTerminateApplicationOptions();2terminateOptions.withTimeout(Duration.ofSeconds(5));3driver.terminateApp("com.example.testapp", terminateOptions);4AndroidTerminateApplicationOptions terminateOptions = new AndroidTerminateApplicationOptions();5terminateOptions.withTimeout(Duration.ofSeconds(5));6driver.terminateApp("com.example.testapp", terminateOptions);7AndroidTerminateApplicationOptions terminateOptions = new AndroidTerminateApplicationOptions();8terminateOptions.withTimeout(Duration.ofSeconds(5));9driver.terminateApp("com.example.testapp", terminateOptions);10AndroidTerminateApplicationOptions terminateOptions = new AndroidTerminateApplicationOptions();11terminateOptions.withTimeout(Duration.ofSeconds(5));12driver.terminateApp("com.example.testapp", terminateOptions);13AndroidTerminateApplicationOptions terminateOptions = new AndroidTerminateApplicationOptions();14terminateOptions.withTimeout(Duration.ofSeconds(5));15driver.terminateApp("com.example.testapp", terminateOptions);16AndroidTerminateApplicationOptions terminateOptions = new AndroidTerminateApplicationOptions();17terminateOptions.withTimeout(Duration.ofSeconds(5));18driver.terminateApp("com.example.testapp", terminateOptions);19AndroidTerminateApplicationOptions terminateOptions = new AndroidTerminateApplicationOptions();20terminateOptions.withTimeout(Duration.ofSeconds(5));21driver.terminateApp("com.example.testapp", terminateOptions);22AndroidTerminateApplicationOptions terminateOptions = new AndroidTerminateApplicationOptions();23terminateOptions.withTimeout(Duration.ofSeconds(5));24driver.terminateApp("com.example.testapp", terminateOptions);25AndroidTerminateApplicationOptions terminateOptions = new AndroidTerminateApplicationOptions();26terminateOptions.withTimeout(Duration.ofSeconds(5));27driver.terminateApp("com.example.testapp", terminateOptions);

Full Screen

Full Screen

withTimeout

Using AI Code Generation

copy

Full Screen

1AndroidTerminateApplicationOptions terminateAppOptions = new AndroidTerminateApplicationOptions();2terminateAppOptions.withTimeout(5, TimeUnit.SECONDS);3driver.terminateApp("com.example.android.contactmanager", terminateAppOptions);4AndroidTerminateApplicationOptions terminateAppOptions = new AndroidTerminateApplicationOptions();5terminateAppOptions.withTimeout(Duration.ofSeconds(5));6driver.terminateApp("com.example.android.contactmanager", terminateAppOptions);7let terminateAppOptions = new AndroidTerminateApplicationOptions();8terminateAppOptions.withTimeout(5, TimeUnit.SECONDS);9await driver.terminateApp("com.example.android.contactmanager", terminateAppOptions);10let terminateAppOptions = new AndroidTerminateApplicationOptions();11terminateAppOptions.withTimeout(Duration.ofSeconds(5));12await driver.terminateApp("com.example.android.contactmanager", terminateAppOptions);13terminate_app_options = AndroidTerminateApplicationOptions()14terminate_app_options.with_timeout(5, TimeUnit.SECONDS)15self.driver.terminate_app("com.example.android.contactmanager", terminate_app_options)16terminate_app_options = AndroidTerminateApplicationOptions()17terminate_app_options.with_timeout(Duration.ofSeconds(5))18self.driver.terminate_app("com.example.android.contactmanager", terminate_app_options)19terminate_app_options.with_timeout(5, TimeUnit.SECONDS)20driver.terminate_app("com.example.android.contactmanager", terminate_app_options)21terminate_app_options.with_timeout(Duration.ofSeconds(5))22driver.terminate_app("com.example.android.contactmanager", terminate_app_options)

Full Screen

Full Screen

withTimeout

Using AI Code Generation

copy

Full Screen

1AndroidTerminateApplicationOptions terminateOptions = new AndroidTerminateApplicationOptions();2terminateOptions.withTimeout(Duration.ofSeconds(5));3driver.terminateApp("com.example.android.apis", terminateOptions);4driver.activateApp("com.example.android.apis");5driver.terminateApp("com.example.android.apis", Duration.ofSeconds(5));6driver.terminateApp("com.example.android.apis", 5, TimeUnit.SECONDS);7driver.terminateApp("com.example.android.apis", Duration.ofSeconds(5));8driver.terminateApp("com.example.android.apis", 5, TimeUnit.SECONDS);9driver.terminateApp("com.example.android.apis", Duration.ofSeconds(5));10driver.terminateApp("com.example.android.apis", 5, TimeUnit.SECONDS);11driver.terminateApp("com.example.android.apis", Duration.ofSeconds(5));12driver.terminateApp("com.example.android.apis", 5, TimeUnit.SECONDS);13driver.terminateApp("com.example.android.apis", Duration.ofSeconds(5));14driver.terminateApp("com.example.android.apis", 5, TimeUnit.SECONDS);15driver.terminateApp("com.example.android.apis", Duration.ofSeconds(5));16driver.terminateApp("com.example.android.apis", 5

Full Screen

Full Screen

withTimeout

Using AI Code Generation

copy

Full Screen

1import io.appium.java_client.android.appmanagement.AndroidTerminateApplicationOptions;2public class TerminateApp {3 public static void main(String[] args) throws MalformedURLException {4 AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();5 options.withTimeout(Duration.ofSeconds(5));6 driver.terminateApp("com.example.android.contactmanager", options);7 }8}9using OpenQA.Selenium.Appium;10using OpenQA.Selenium.Appium.Android;11{12 public static void Main(string[] args)13 {14 AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();15 options.withTimeout(Duration.ofSeconds(5));16 driver.terminateApp("com.example.android.contactmanager", options);17 }18}19from appium.webdriver.extensions.android.appmanagement import AndroidTerminateApplicationOptions20options = AndroidTerminateApplicationOptions()21options.withTimeout(Duration.ofSeconds(5))22driver.terminate_app("com.example.android.contactmanager", options)23options.withTimeout(Duration.ofSeconds(5))24driver.terminate_app("com.example.android.contactmanager", options)25options = AndroidTerminateApplicationOptions()26options.withTimeout(Duration.ofSeconds(5))27driver.terminate_app("com.example.android.contactmanager", options)28use Facebook\WebDriver\Remote\WebDriverCapabilityType;29use Facebook\WebDriver\Remote\DesiredCapabilities;30use Facebook\WebDriver\Chrome\ChromeOptions;

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.

Run io.appium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in AndroidTerminateApplicationOptions

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful