Best io.appium code snippet using io.appium.java_client.android.appmanagement.AndroidTerminateApplicationOptions.withTimeout
AndroidStepHandler.java
Source:AndroidStepHandler.java
...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 }...
IOSStepHandler.java
Source:IOSStepHandler.java
...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 }...
AndroidTerminateApplicationOptions.java
Source:AndroidTerminateApplicationOptions.java
...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}...
AndInteractsWithApps.java
Source:AndInteractsWithApps.java
...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}...
withTimeout
Using AI Code Generation
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");
withTimeout
Using AI Code Generation
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);
withTimeout
Using AI Code Generation
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)
withTimeout
Using AI Code Generation
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
withTimeout
Using AI Code Generation
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);
withTimeout
Using AI Code Generation
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)
withTimeout
Using AI Code Generation
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
withTimeout
Using AI Code Generation
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;
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!