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

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

AndroidStepHandler.java

Source:AndroidStepHandler.java Github

copy

Full Screen

...15import io.appium.java_client.*;16import io.appium.java_client.android.AndroidDriver;17import io.appium.java_client.android.AndroidStartScreenRecordingOptions;18import io.appium.java_client.android.appmanagement.AndroidInstallApplicationOptions;19import io.appium.java_client.android.appmanagement.AndroidTerminateApplicationOptions;20import io.appium.java_client.android.nativekey.AndroidKey;21import io.appium.java_client.android.nativekey.KeyEvent;22import io.appium.java_client.remote.AndroidMobileCapabilityType;23import io.appium.java_client.remote.AutomationName;24import io.appium.java_client.remote.MobileCapabilityType;25import io.appium.java_client.touch.WaitOptions;26import io.appium.java_client.touch.offset.PointOption;27import org.cloud.sonic.agent.tools.*;28import org.jsoup.Jsoup;29import org.jsoup.nodes.Attribute;30import org.jsoup.nodes.Document;31import org.openqa.selenium.*;32import org.openqa.selenium.chrome.ChromeOptions;33import org.openqa.selenium.remote.DesiredCapabilities;34import org.springframework.core.env.Environment;35import org.springframework.core.io.FileSystemResource;36import org.springframework.http.ResponseEntity;37import org.springframework.util.*;38import org.springframework.web.client.RestTemplate;39import java.io.File;40import java.io.FileOutputStream;41import java.io.IOException;42import java.time.Duration;43import java.util.*;44import java.util.concurrent.Future;45import java.util.concurrent.TimeUnit;46import static org.testng.Assert.*;47/**48 * @author ZhouYiXun49 * @des 安卓自动化处理类50 * @date 2021/8/16 20:1051 */52public class AndroidStepHandler {53 public LogTool log = new LogTool();54 private AndroidDriver androidDriver;55 private JSONObject globalParams = new JSONObject();56 //包版本57// private String version = "";58 //测试起始时间59 private long startTime;60 //测试的包名61 private String testPackage = "";62 private String udId = "";63 //测试状态64 private int status = 1;65 public void setTestMode(int caseId, int resultId, String udId, String type, String sessionId) {66 log.caseId = caseId;67 log.resultId = resultId;68 log.udId = udId;69 log.type = type;70 log.sessionId = sessionId;71 }72 public void setGlobalParams(JSONObject jsonObject) {73 globalParams = jsonObject;74 }75 /**76 * @return77 * @author ZhouYiXun78 * @des new时开始计时79 * @date 2021/8/16 20:0180 */81 public AndroidStepHandler() {82 startTime = Calendar.getInstance().getTimeInMillis();83 }84 /**85 * @param udId86 * @return void87 * @author ZhouYiXun88 * @des 启动安卓驱动,连接设备89 * @date 2021/8/16 20:0190 */91 public void startAndroidDriver(String udId) throws InterruptedException {92 this.udId = udId;93 DesiredCapabilities desiredCapabilities = new DesiredCapabilities();94 //微信webView配置95 ChromeOptions chromeOptions = new ChromeOptions();96 chromeOptions.setExperimentalOption("androidProcess", "com.tencent.mm:tools");97 desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);98 //webView通用配置,自动下载匹配的driver99 desiredCapabilities.setCapability(AndroidMobileCapabilityType.RECREATE_CHROME_DRIVER_SESSIONS, true);100 desiredCapabilities.setCapability(AndroidMobileCapabilityType.CHROMEDRIVER_EXECUTABLE_DIR, "webview");101 desiredCapabilities.setCapability(AndroidMobileCapabilityType.CHROMEDRIVER_CHROME_MAPPING_FILE, "webview/version.json");102 //平台103 desiredCapabilities.setCapability(AndroidMobileCapabilityType.PLATFORM_NAME, Platform.ANDROID);104 //选用的自动化框架105 desiredCapabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.ANDROID_UIAUTOMATOR2);106 //关闭运行时阻塞其他Accessibility服务,开启的话其他不能使用了107 desiredCapabilities.setCapability("disableSuppressAccessibilityService", true);108 //adb指令超时时间109 desiredCapabilities.setCapability(AndroidMobileCapabilityType.ADB_EXEC_TIMEOUT, 7200000);110 //UIA2安装超时时间111 desiredCapabilities.setCapability("uiautomator2ServerInstallTimeout", 600000);112 //io.appium.uiautomator2.server io.appium.uiautomator2.server.test //io.appium.settings113// desiredCapabilities.setCapability("skipServerInstallation",true);114// desiredCapabilities.setCapability("disableWindowAnimation",true);115// desiredCapabilities.setCapability("skipDeviceInitialization",true);116 //等待新命令超时时间117 desiredCapabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 7200);118 //不重置应用119 desiredCapabilities.setCapability(MobileCapabilityType.NO_RESET, true);120 //单独唤起应用的话,这个需要设置空字符串121 desiredCapabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "");122 //指定设备序列号123 desiredCapabilities.setCapability(MobileCapabilityType.UDID, udId);124 //随机systemPort125 desiredCapabilities.setCapability(AndroidMobileCapabilityType.SYSTEM_PORT, PortTool.getPort());126 desiredCapabilities.setCapability("skipLogcatCapture", true);127 try {128 androidDriver = new AndroidDriver(AppiumServer.service.getUrl(), desiredCapabilities);129 androidDriver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);130 log.sendStepLog(StepType.PASS, "连接设备驱动成功", "");131 } catch (Exception e) {132 log.sendStepLog(StepType.ERROR, "连接设备驱动失败!", "");133 //测试标记为失败134 setResultDetailStatus(ResultDetailStatus.FAIL);135 throw e;136 }137 Capabilities capabilities = androidDriver.getCapabilities();138 Thread.sleep(100);139 log.androidInfo("Android", capabilities.getCapability("platformVersion").toString(),140 udId, capabilities.getCapability("deviceManufacturer").toString(),141 capabilities.getCapability("deviceModel").toString(),142 capabilities.getCapability("deviceApiLevel").toString(),143 capabilities.getCapability("deviceScreenSize").toString());144 }145 /**146 * @return void147 * @author ZhouYiXun148 * @des 关闭driver149 * @date 2021/8/16 20:21150 */151 public void closeAndroidDriver() {152 try {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

...18import org.cloud.sonic.agent.tools.UploadTools;19import io.appium.java_client.MultiTouchAction;20import io.appium.java_client.Setting;21import io.appium.java_client.TouchAction;22import io.appium.java_client.android.appmanagement.AndroidTerminateApplicationOptions;23import io.appium.java_client.appmanagement.BaseInstallApplicationOptions;24import io.appium.java_client.appmanagement.BaseTerminateApplicationOptions;25import io.appium.java_client.ios.IOSDriver;26import io.appium.java_client.ios.IOSStartScreenRecordingOptions;27import io.appium.java_client.remote.AutomationName;28import io.appium.java_client.remote.IOSMobileCapabilityType;29import io.appium.java_client.remote.MobileCapabilityType;30import io.appium.java_client.touch.WaitOptions;31import io.appium.java_client.touch.offset.PointOption;32import org.jsoup.Jsoup;33import org.jsoup.nodes.Attribute;34import org.jsoup.nodes.Document;35import org.openqa.selenium.OutputType;36import org.openqa.selenium.Platform;37import org.openqa.selenium.TakesScreenshot;38import org.openqa.selenium.WebElement;39import org.openqa.selenium.remote.DesiredCapabilities;40import org.springframework.core.env.Environment;41import org.springframework.core.io.FileSystemResource;42import org.springframework.http.ResponseEntity;43import org.springframework.util.Base64Utils;44import org.springframework.util.FileCopyUtils;45import org.springframework.util.LinkedMultiValueMap;46import org.springframework.util.MultiValueMap;47import org.springframework.web.client.RestTemplate;48import java.io.File;49import java.io.FileOutputStream;50import java.io.IOException;51import java.time.Duration;52import java.util.Calendar;53import java.util.HashMap;54import java.util.List;55import java.util.Map;56import java.util.concurrent.TimeUnit;57import static org.testng.Assert.*;58/**59 * @author ZhouYiXun60 * @des iOS自动化处理类61 * @date 2021/8/16 20:1062 */63public class IOSStepHandler {64 public LogTool log = new LogTool();65 private IOSDriver iosDriver;66 private JSONObject globalParams = new JSONObject();67 private String testPackage = "";68 private String udId = "";69 //测试状态70 private int status = 1;71 public void setTestMode(int caseId, int resultId, String udId, String type, String sessionId) {72 log.caseId = caseId;73 log.resultId = resultId;74 log.udId = udId;75 log.type = type;76 log.sessionId = sessionId;77 }78 public void setGlobalParams(JSONObject jsonObject) {79 globalParams = jsonObject;80 }81 public void startIOSDriver(String udId, int wdaPort) throws InterruptedException, IOException {82 this.udId = udId;83 DesiredCapabilities desiredCapabilities = new DesiredCapabilities();84 desiredCapabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, Platform.IOS);85 desiredCapabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.IOS_XCUI_TEST);86 desiredCapabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 3600);87 desiredCapabilities.setCapability(MobileCapabilityType.NO_RESET, true);88 desiredCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, TIDeviceTool.getName(udId));89 desiredCapabilities.setCapability(MobileCapabilityType.UDID, udId);90 desiredCapabilities.setCapability("wdaConnectionTimeout", 60000);91 desiredCapabilities.setCapability(IOSMobileCapabilityType.WEB_DRIVER_AGENT_URL, "http://127.0.0.1:" + wdaPort);92 desiredCapabilities.setCapability("useXctestrunFile", false);93 desiredCapabilities.setCapability(IOSMobileCapabilityType.SHOW_IOS_LOG, false);94 desiredCapabilities.setCapability(IOSMobileCapabilityType.SHOW_XCODE_LOG, false);95 desiredCapabilities.setCapability("skipLogCapture", true);96 desiredCapabilities.setCapability(IOSMobileCapabilityType.USE_PREBUILT_WDA, false);97 try {98 iosDriver = new IOSDriver(AppiumServer.service.getUrl(), desiredCapabilities);99 iosDriver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);100 iosDriver.setSetting(Setting.MJPEG_SERVER_FRAMERATE, 50);101 iosDriver.setSetting(Setting.MJPEG_SCALING_FACTOR, 50);102 iosDriver.setSetting(Setting.MJPEG_SERVER_SCREENSHOT_QUALITY, 10);103 iosDriver.setSetting("snapshotMaxDepth", 30);104 log.sendStepLog(StepType.PASS, "连接设备驱动成功", "");105 } catch (Exception e) {106 log.sendStepLog(StepType.ERROR, "连接设备驱动失败!", "");107 //测试标记为失败108 setResultDetailStatus(ResultDetailStatus.FAIL);109 throw e;110 }111 int width = iosDriver.manage().window().getSize().width;112 int height = iosDriver.manage().window().getSize().height;113 IOSSizeMap.getMap().put(udId, width + "x" + height);114 }115 public void closeIOSDriver() {116 try {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

...20import com.google.common.collect.ImmutableMap;21import io.appium.java_client.appmanagement.BaseTerminateApplicationOptions;22import java.time.Duration;23import java.util.Map;24public class AndroidTerminateApplicationOptions extends25 BaseTerminateApplicationOptions<AndroidTerminateApplicationOptions> {26 private Duration timeout;27 /**28 * The time to wait until the app is terminated (500ms by default).29 *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

AndInteractionWithApps.java

Source:AndInteractionWithApps.java Github

copy

Full Screen

1import io.appium.java_client.AppiumDriver;2import io.appium.java_client.MobileBy;3import io.appium.java_client.android.appmanagement.AndroidInstallApplicationOptions;4import io.appium.java_client.android.appmanagement.AndroidTerminateApplicationOptions;5import org.openqa.selenium.By;6import java.io.File;7import java.time.Duration;8import java.util.concurrent.TimeUnit;9public class AndInteractionWithApps {10 public static void main(String[] args) throws Exception {11 AppiumDriver driver = CreateDriverSession.initializeDriver("Android");12 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);13 By views = MobileBy.AccessibilityId("Views");14 driver.findElement(views).click();15 Thread.sleep(2000);16 System.out.println(driver.queryAppState("io.appium.android.apis"));17 driver.terminateApp("io.appium.android.apis");18 Thread.sleep(2000);...

Full Screen

Full Screen

AndInteractsWithApps.java

Source:AndInteractsWithApps.java Github

copy

Full Screen

1import io.appium.java_client.AppiumDriver;2import io.appium.java_client.MobileBy;3import io.appium.java_client.android.appmanagement.AndroidInstallApplicationOptions;4import io.appium.java_client.android.appmanagement.AndroidTerminateApplicationOptions;5import org.openqa.selenium.By;6import java.io.File;7import java.net.MalformedURLException;8import java.time.Duration;9import java.util.concurrent.TimeUnit;10public class AndInteractsWithApps {11 public static void main(String[] args) throws Exception {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

AndroidTerminateApplicationOptions

Using AI Code Generation

copy

Full Screen

1import io.appium.java_client.android.AndroidDriver;2import io.appium.java_client.android.AndroidElement;3import io.appium.java_client.android.appmanagement.AndroidTerminateApplicationOptions;4import io.appium.java_client.remote.MobileCapabilityType;5import org.openqa.selenium.remote.DesiredCapabilities;6import java.net.MalformedURLException;7import java.net.URL;8import java.util.concurrent.TimeUnit;9public class TerminateApplication {10 public static void main(String[] args) throws MalformedURLException {11 DesiredCapabilities cap = new DesiredCapabilities();12 cap.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Device");13 cap.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");14 cap.setCapability(MobileCapabilityType.AUTOMATION_NAME, "UiAutomator2");15 cap.setCapability("appPackage", "com.android.calculator2");16 cap.setCapability("appActivity", "com.android.calculator2.Calculator");

Full Screen

Full Screen

AndroidTerminateApplicationOptions

Using AI Code Generation

copy

Full Screen

1package appium;2import org.openqa.selenium.remote.DesiredCapabilities;3import io.appium.java_client.android.AndroidDriver;4import io.appium.java_client.android.appmanagement.AndroidTerminateApplicationOptions;5public class TerminateApp {6 public static void main(String[] args) {7 DesiredCapabilities caps = new DesiredCapabilities();8 caps.setCapability("deviceName", "emulator-5554");9 caps.setCapability("platformName", "Android");10 caps.setCapability("appPackage", "com.android.calculator2");11 caps.setCapability("appActivity", "com.android.calculator2.Calculator");12 caps.setCapability("noReset", "true");13 AndroidDriver driver = new AndroidDriver(caps);14 AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();15 options.setAppPackage("com.android.calculator2");16 driver.terminateApp(options);17 }18}

Full Screen

Full Screen

AndroidTerminateApplicationOptions

Using AI Code Generation

copy

Full Screen

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

Full Screen

Full Screen

AndroidTerminateApplicationOptions

Using AI Code Generation

copy

Full Screen

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

Full Screen

Full Screen

AndroidTerminateApplicationOptions

Using AI Code Generation

copy

Full Screen

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

Full Screen

Full Screen

AndroidTerminateApplicationOptions

Using AI Code Generation

copy

Full Screen

1AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();2options.setBundleId("com.example.app");3driver.terminateApp(options);4AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();5options.setBundleId("com.example.app");6driver.terminateApp(options);7AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();8options.setBundleId("com.example.app");9driver.terminateApp(options);10AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();11options.setBundleId("com.example.app");12driver.terminateApp(options);13AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();14options.setBundleId("com.example.app");15driver.terminateApp(options);16AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();17options.setBundleId("com.example.app");18driver.terminateApp(options);19AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();20options.setBundleId("com.example.app");21driver.terminateApp(options);22AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();23options.setBundleId("com.example.app");24driver.terminateApp(options);25AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();26options.setBundleId("com.example.app");27driver.terminateApp(options);28AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();29options.setBundleId("com.example.app");30driver.terminateApp(options);31AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();32options.setBundleId("com.example.app");33driver.terminateApp(options);

Full Screen

Full Screen

AndroidTerminateApplicationOptions

Using AI Code Generation

copy

Full Screen

1AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();2options.withBundleId("com.example.app");3driver.terminateApp(options);4const options = new AndroidTerminateApplicationOptions();5options.withBundleId("com.example.app");6driver.terminateApp(options);7options = AndroidTerminateApplicationOptions()8options.with_bundleId("com.example.app")9driver.terminate_app(options)10options = AndroidTerminateApplicationOptions()11options.with_bundleId("com.example.app")12driver.terminate_app(options)13AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();14options.withBundleId("com.example.app");15driver.TerminateApp(options);16$options = new AndroidTerminateApplicationOptions();17$options->withBundleId("com.example.app");18$driver->terminateApp($options);19options = AndroidTerminateApplicationOptions()20options.with_bundleId("com.example.app")21driver.terminate_app(options)22AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();23options.withBundleId("com.example.app");24driver.TerminateApp(options);25$options = new AndroidTerminateApplicationOptions();26$options->withBundleId("com.example.app");27$driver->terminateApp($options);28options = AndroidTerminateApplicationOptions()29options.with_bundleId("com.example.app")30driver.terminate_app(options)

Full Screen

Full Screen

AndroidTerminateApplicationOptions

Using AI Code Generation

copy

Full Screen

1AndroidTerminateApplicationOptions options = new AndroidTerminateApplicationOptions();2options.setBundleId("com.example.application");3driver.terminateApp(options);4await driver.terminateApp({5});6driver.terminate_app({7})8driver.terminate_app({9})10driver.terminateApp({11})12driver.terminate_app({13})14driver.terminate_app({15})16driver.terminateApp({17})18driver.terminate_app({19})20driver.terminate_app({21})

Full Screen

Full Screen

AndroidTerminateApplicationOptions

Using AI Code Generation

copy

Full Screen

1AndroidTerminateApplicationOptions terminateApplicationOptions = new AndroidTerminateApplicationOptions();2terminateApplicationOptions.setBundleId("com.example.app");3driver.terminateApp(terminateApplicationOptions);4AndroidActivateApplicationOptions activateApplicationOptions = new AndroidActivateApplicationOptions();5activateApplicationOptions.setBundleId("com.example.app");6driver.activateApp(activateApplicationOptions);7AndroidGetApplicationStateOptions getApplicationStateOptions = new AndroidGetApplicationStateOptions();8getApplicationStateOptions.setBundleId("com.example.app");9driver.getApplicationState(getApplicationStateOptions);10AndroidGetAppStateOptions getAppStateOptions = new AndroidGetAppStateOptions();11getAppStateOptions.setBundleId("com.example.app");12driver.getAppState(getAppStateOptions);13AndroidGetApplicationStringsOptions getApplicationStringsOptions = new AndroidGetApplicationStringsOptions();14getApplicationStringsOptions.setLanguage("en");15getApplicationStringsOptions.setLanguage("en");16getApplicationStringsOptions.setLanguage("en");17driver.getApplicationStrings(getApplicationStringsOptions);18AndroidGetDeviceTimeOptions getDeviceTimeOptions = new AndroidGetDeviceTimeOptions();19getDeviceTimeOptions.setLocalTimezone(true);20driver.getDeviceTime(getDeviceTimeOptions);21AndroidInstallApplicationOptions installApplicationOptions = new AndroidInstallApplicationOptions();22installApplicationOptions.setApp("/path/to/app");23installApplicationOptions.setReplace(true);24driver.installApp(installApplicationOptions);25AndroidRemoveApplicationOptions removeApplicationOptions = new AndroidRemoveApplicationOptions();26removeApplicationOptions.setBundleId("com.example.app");27driver.removeApp(removeApplicationOptions);28AndroidBackgroundApplicationOptions backgroundApplicationOptions = new AndroidBackgroundApplicationOptions();29backgroundApplicationOptions.setBundleId("com.example.app");30backgroundApplicationOptions.setSeconds(5);31driver.backgroundApp(backgroundApplicationOptions);

Full Screen

Full Screen

AndroidTerminateApplicationOptions

Using AI Code Generation

copy

Full Screen

1AndroidTerminateApplicationOptions terminateApplicationOptions = new AndroidTerminateApplicationOptions();2terminateApplicationOptions.setBundleId("com.example.android.apis");3driver.terminateApp(terminateApplicationOptions);4AndroidTerminateApplicationOptions terminateApplicationOptions = new AndroidTerminateApplicationOptions();5terminateApplicationOptions.setBundleId("com.example.android.apis");6terminateApplicationOptions.setOptions("com.example.android.apis2");7driver.terminateApp(terminateApplicationOptions);8AndroidTerminateApplicationOptions terminateApplicationOptions = new AndroidTerminateApplicationOptions();9terminateApplicationOptions.setBundleId("com.example.android.apis");10terminateApplicationOptions.setOptions("com.example.android.apis2");11driver.terminateApp(terminateApplicationOptions);12AndroidTerminateApplicationOptions terminateApplicationOptions = new AndroidTerminateApplicationOptions();13terminateApplicationOptions.setBundleId("com.example.android.apis");14terminateApplicationOptions.setOptions("com.example.android.apis2");15driver.terminateApp(terminateApplicationOptions);

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 methods 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