How to use AppiumDriver class of io.appium.java_client package

Best io.appium code snippet using io.appium.java_client.AppiumDriver

Run io.appium automation tests on LambdaTest cloud grid

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

Session.java

Source: Session.java Github

copy
1package sessions;
2
3import controlsAppium.Label;
4import factoryDevices.FactoryDevice;
5import io.appium.java_client.AppiumDriver;
6import io.appium.java_client.TouchAction;
7import io.appium.java_client.touch.WaitOptions;
8import io.appium.java_client.touch.offset.PointOption;
9import org.openqa.selenium.By;
10
11import java.net.MalformedURLException;
12import java.time.Duration;
13
14public class Session {
15    private static Session instance = null;
16    private AppiumDriver driver;
17
18    private Session() throws MalformedURLException {
19        driver = FactoryDevice.make(FactoryDevice.DeviceType.ANDROID).create();
20    }
21
22    public static Session getInstance() throws MalformedURLException {
23        if (instance == null)
24            instance = new Session();
25        return instance;
26    }
27
28    public void close() {
29        driver.quit();
30        instance = null;
31    }
32
33    public AppiumDriver getDriver() {
34        return driver;
35    }
36}
37
Full Screen

AppEntrance.java

Source: AppEntrance.java Github

copy
1package com.ushio.appium;
2
3import com.ushio.appium.page.LaunchPage;
4import com.ushio.util.ThreadUtil;
5import io.appium.java_client.AppiumDriver;
6import io.appium.java_client.MobileElement;
7import io.appium.java_client.remote.AndroidMobileCapabilityType;
8import io.appium.java_client.remote.MobileCapabilityType;
9import io.appium.java_client.remote.MobilePlatform;
10import org.openqa.selenium.remote.DesiredCapabilities;
11import org.openqa.selenium.support.ui.WebDriverWait;
12
13import java.net.URL;
14import java.util.concurrent.TimeUnit;
15
16/**
17 * @author: ushio
18 * @description:app入口类,单例类
19 **/
20public class AppEntrance {
21
22    private volatile static AppEntrance appEntrance;
23
24    private static AppiumDriver<MobileElement> appiumDriver;
25    private static WebDriverWait webDriverWait;
26
27    public static AppEntrance getInstance() {
28        if (appEntrance == null) {
29            synchronized (AppEntrance.class) {
30                if (appEntrance == null) {
31                    appEntrance = new AppEntrance();
32                }
33            }
34        }
35        return appEntrance;
36    }
37
38    private AppEntrance(){
39        initWebDriver();
40    }
41
42    private void initWebDriver() {
43        if (appiumDriver == null) {
44            DesiredCapabilities capabilities = new DesiredCapabilities();
45            capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, AppiumConstant.DEVICE_NAME);
46            capabilities.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, AppiumConstant.APP_PACKAGE);
47            capabilities.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, AppiumConstant.APP_ACTIVITY);
48            capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, AppiumConstant.PLATFORM_NAME);
49            capabilities.setCapability(MobileCapabilityType.NO_RESET, AppiumConstant.NO_RESET);
50//        capabilities.setCapability(AndroidMobileCapabilityType.DONT_STOP_APP_ON_RESET, true);
51            try {
52                appiumDriver = new AppiumDriver<>(new URL(AppiumConstant.URL),
53                        capabilities);
54                appiumDriver.manage().timeouts().implicitlyWait(AppiumConstant.IMPLICITLY_WAIT, TimeUnit.SECONDS);
55                webDriverWait = new WebDriverWait(appiumDriver, 60,1000);
56            } catch (Exception e) {
57                e.printStackTrace();
58            }
59        }
60    }
61
62    public void quit() {
63        if (appiumDriver != null) {
64            ThreadUtil.sleep(15000);
65            appiumDriver.quit();
66        }
67    }
68
69    public LaunchPage launchApp(){
70        return new LaunchPage(appiumDriver,webDriverWait);
71    }
72
73}
74
Full Screen

MobileBase.java

Source: MobileBase.java Github

copy
1package com.utilities;
2
3import java.io.File;
4import java.io.IOException;
5import java.net.ServerSocket;
6import java.net.URL;
7import java.util.HashMap;
8import java.util.concurrent.TimeUnit;
9
10import org.apache.log4j.Logger;
11import org.json.JSONObject;
12import org.openqa.selenium.By;
13import org.openqa.selenium.JavascriptExecutor;
14import org.openqa.selenium.Point;
15import org.openqa.selenium.WebElement;
16import org.openqa.selenium.remote.DesiredCapabilities;
17import org.openqa.selenium.support.ui.ExpectedConditions;
18import org.openqa.selenium.support.ui.WebDriverWait;
19
20import com.configurations.Constants;
21import com.relevantcodes.extentreports.ExtentReports;
22import com.relevantcodes.extentreports.ExtentTest;
23import com.relevantcodes.extentreports.LogStatus;
24import com.restassured.services.ReportPaths;
25
26import io.appium.java_client.AppiumDriver;
27import io.appium.java_client.MobileBy;
28import io.appium.java_client.MobileElement;
29import io.appium.java_client.TouchAction;
30import io.appium.java_client.android.AndroidDriver;
31import io.appium.java_client.ios.IOSDriver;
32import io.appium.java_client.ios.IOSElement;
33import io.appium.java_client.remote.AndroidMobileCapabilityType;
34import io.appium.java_client.remote.AutomationName;
35import io.appium.java_client.remote.MobileCapabilityType;
36import io.appium.java_client.service.local.AppiumDriverLocalService;
37import io.appium.java_client.service.local.AppiumServiceBuilder;
38import io.appium.java_client.touch.offset.PointOption;
39
40public class MobileBase {
41	
42	public static String projectPath = System.getProperty("user.dir");
43	public static String mobileReportsPath = projectPath + File.separator + "MobileReports" + File.separator + ReportPaths.reportPathName;
44	private String nodeJSPath = System.getenv("NODE_PATH");
45	private String appiumServerJSPath = System.getenv("APPIUM_JS_PATH");
46	private AppiumDriverLocalService appiumDriverService;
47	public AppiumDriver<MobileElement> appiumDriver;
48	private ConfigFilesUtility configFileObj;
49	
50	/**************************************************** Desired Capabilities (Android/iOS) ************************************************/
51	/*
52	 * Set up desired capabilities and pass the Android app-activity and app-package to Appium
53	 * Create AppiumDriver instance and connect to the Appium server
54	 * It will launch the Application in Android Device using the configurations specified in Desired Capabilities
55	 */
56
57	public AppiumDriver<MobileElement> launchMobileDriver(ExtentReports reports) throws Exception {
58		configFileObj = new ConfigFilesUtility();
59		configFileObj.loadPropertyFile("DeviceCapabilities.properties");
60		appiumDriverService = setUpAppiumDriver();
61		startAppiumServer();
62		
63		DesiredCapabilities capabilities = new DesiredCapabilities();
64		
65		
66		capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, configFileObj.getProperty("deviceName").trim());		
67		capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, configFileObj.getProperty("platformName").trim());		
68		capabilities.setCapability(MobileCapabilityType.FULL_RESET,  configFileObj.getProperty("fullreset").trim());	     
69		capabilities.setCapability(MobileCapabilityType.UDID, configFileObj.getProperty("udid").trim());
70		capabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 60*10); //ending the session 10 minutes
71		capabilities.setCapability(MobileCapabilityType.APP, projectPath + File.separator + "mobile" + File.separator + (configFileObj.getProperty("app").trim().contains(".ipa") ? "ios" : "android") + File.separator +  configFileObj.getProperty("app").trim());
72		
73		if(configFileObj.getProperty("app").trim().contains(".ipa")) {
74			capabilities.setCapability("bundleid", configFileObj.getProperty("appPackage").trim());
75			capabilities.setCapability("wdaLaunchTimeout",60000); // launching webdriver agent time
76			capabilities.setCapability("wdaStartupRetries", 2); //webdriveragent retries 4 times
77			capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "XCUITest");
78			
79			appiumDriver = new IOSDriver<MobileElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
80		} else {
81			capabilities.setCapability(AndroidMobileCapabilityType.AUTO_GRANT_PERMISSIONS,true);
82			capabilities.setCapability("autoAcceptAlerts", true);
83			capabilities.setCapability("appPackage", configFileObj.getProperty("appPackage").trim());
84			capabilities.setCapability("appActivity", configFileObj.getProperty("appActivity").trim());
85			capabilities.setCapability("appWaitActivity", configFileObj.getProperty("appActivity").trim());
86			//capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.ANDROID_UIAUTOMATOR2);
87			//capabilities.setCapability("unicodeKeyboard", "true");
88			//capabilities.setCapability("resetKeyboard", "true");
89			String platformVersion = configFileObj.getProperty("platformVersion");	
90			if ((platformVersion != null) && !(platformVersion.trim().isEmpty())) {
91				capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, configFileObj.getProperty("platformVersion").trim());
92			} else {
93				capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, configFileObj.getProperty("VERSION").trim());
94			}
95			if ((platformVersion != null) && !platformVersion.trim().isEmpty() && !(Integer.valueOf(platformVersion.trim().split("\\.")[0]) >= 7) ) {
96				capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.ANDROID_UIAUTOMATOR2);
97			} else if (Double.valueOf(configFileObj.getProperty("VERSION").trim()) >= 7 ) {
98				capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.ANDROID_UIAUTOMATOR2);
99			}
100			appiumDriver = new AndroidDriver<MobileElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
101		}
102		//appiumDriver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
103		ExtentTest test = reports.startTest("Device Information");
104		System.out.println("sessionDetails" + new JSONObject(appiumDriver.getSessionDetails()));
105		JSONObject sessionObj = new JSONObject(appiumDriver.getSessionDetails());
106		String deviceScreenSize = sessionObj.optString("deviceScreenSize");
107		String pltformVersion = configFileObj.getProperty("platformVersion");
108		String deviceModel = sessionObj.optString("deviceModel");
109		String deviceManufacturer = sessionObj.optString("deviceManufacturer");
110		String platformName = sessionObj.optString("platformName");
111		
112		if(configFileObj.getProperty("app").trim().contains(".ipa")) {
113			JSONObject rectObj = sessionObj.optJSONObject("viewportRect");
114			deviceScreenSize = "Width: " + rectObj.optString("width") + ", Height: " + rectObj.optString("height") + ", Top: " + rectObj.optString("top");
115			deviceModel = sessionObj.optString("deviceName");
116		} else {
117			test.log(LogStatus.INFO, "Device Manufacture : " + deviceManufacturer);
118		}
119		test.log(LogStatus.INFO, "Device Model : " + deviceModel);
120		//test.log(LogStatus.INFO, "Device Screen Size : " + deviceScreenSize);
121		test.log(LogStatus.INFO, "Platform Name : " + platformName);
122		test.log(LogStatus.INFO, "Platform Version : " + pltformVersion);
123		
124		return appiumDriver;
125	}
126	
127	
128	/********************************** Hide Keyboard (Android/iOS) ****************************/
129	public void hideKeyboard() {
130		if(appiumDriver != null) {
131			if(configFileObj.getProperty("app").contains(".ipa")) {
132				hideKeyBoard();
133			} else {
134				appiumDriver.hideKeyboard();
135			}
136		}
137	}
138	
139	@SuppressWarnings("rawtypes")
140	public void hideKeyBoard() {
141		IOSElement element = (IOSElement) appiumDriver.findElementByClassName("XCUIElementTypeKeyboard");
142		Point keyboardPoint = element.getLocation();
143		TouchAction touchAction = new TouchAction(appiumDriver);
144		touchAction.tap(PointOption.point(keyboardPoint.getX() + 2, keyboardPoint.getY() - 2)).perform();
145		try {
146			Thread.sleep(500);
147		} catch (InterruptedException e) {
148			e.printStackTrace();
149		}
150	}
151	
152	/************************************** APPIUM SETUP ***************************************/
153	// Appium server setup service 
154	private AppiumDriverLocalService setUpAppiumDriver() {
155		 // Only for iOS/Mac
156		if(configFileObj.getProperty("app").contains(".ipa") || isMac()) {
157			nodeJSPath = configFileObj.getProperty("nodePath").trim();
158			appiumServerJSPath = configFileObj.getProperty("appiumJSPATH").trim();
159		}
160		
161		appiumDriverService = AppiumDriverLocalService.buildService(new AppiumServiceBuilder()
162				.usingDriverExecutable(new File(nodeJSPath))
163				.withAppiumJS(new File(appiumServerJSPath))
164				.withIPAddress("127.0.0.1")
165				.usingPort(4723));
166		return appiumDriverService;
167	}
168	
169	public boolean checkIfServerIsRunnning(int port) {
170		
171		boolean isServerRunning = false;
172		ServerSocket serverSocket;
173		try {
174			serverSocket = new ServerSocket(port);
175			serverSocket.close();
176		} catch (IOException e) {
177			//If control comes here, then it means the port is in use
178			isServerRunning = true;
179		} finally {
180			serverSocket = null;
181		}
182		return isServerRunning;
183	}	
184 
185	
186	// used to start appium server
187	private boolean startAppiumServer() {
188		if (appiumDriverService != null) {
189			appiumDriverService.start();
190			return appiumDriverService.isRunning();
191		}
192		return false;
193	}
194	
195	// used to stop appium server
196	protected void stopAppiumServer() {
197		if (appiumDriverService != null) {
198			appiumDriverService.stop();
199			System.out.println(" Stopped Appium Server");
200		}   
201	}
202	
203	// add screen count for Report
204	public void addScreensExecutionCount(){
205		Constants.TOTAL_TC = Constants.TOTAL_TC + 1;
206		Constants.IS_TESTCASE = true; Constants.iS_WEB = true;
207	}
208	
209	
210	/**************************************************** For iOS **************************************************/
211	
212	protected MobileElement findElement(String xpath) {
213		MobileElement element = null;
214		try {
215			try {
216				element = appiumDriver.findElementByXPath(xpath);
217			} catch (Exception e) {
218				waitForExpectedElement(appiumDriver, xpath, 60);
219				element = appiumDriver.findElementByXPath(xpath);
220			}
221			if (element.isDisplayed()) {
222				return element;
223			} else {
224				for (int i = 0; i < 5; i++) {
225					scrollDown();
226				}
227			}
228		} catch (Exception e) {
229			e.printStackTrace();
230		}
231
232		return element;
233	}
234	
235	// It's not working latest appium versions
236	public void scrolliniOS(String xpath) {
237		MobileElement elements = appiumDriver.findElementByXPath(xpath);
238		for (int second = 0;; second++) {
239			if (second >= 25){
240				break;
241			}
242			JavascriptExecutor js = (JavascriptExecutor) appiumDriver;
243
244			HashMap<String, Object> scrollObjects = new HashMap<String,Object>();
245			scrollObjects.put("direction", "down");
246			scrollObjects.put("element", elements);
247			js.executeScript("mobile: scroll", scrollObjects);
248			try {
249				Thread.sleep(1000);
250			} catch (InterruptedException e) {
251				e.printStackTrace();
252				System.out.println("scroll wont work for you");
253
254			}
255		}
256	}
257	
258	/**************************************************** For ANDROID **********************************************/
259	
260	/************************************ Find element by Text **********************************************/
261	
262	/**
263	 * used to find element by text  
264	 * Less than android version 7 - Used UiScrollable for scrolling
265	 * Greater than or equalTo android version 7 - Used TouchAction for scrolling to find the element
266	 * @param xpath
267	 * @return MobileElement
268	 */
269	// used to finding the element in screen automatically scrolls full page for finding the element by Text
270	protected MobileElement findElementByText(String xpath) {
271		
272		MobileElement element = null;
273		int maxSwipes =  10;
274		String text = xpath.split("'")[1]; //Extracting the text from xpath
275		try {		
276			if (Double.valueOf(getVersion()) >= 7) {
277				for (int i = 0;  i < maxSwipes; i++) {
278					if(isElementFound(xpath)) {
279					  element = appiumDriver.findElement(MobileBy.AndroidUIAutomator("new UiScrollable(new UiSelector()."
280								+ "scrollable(true).instance(0))"
281								+ ".scrollIntoView(new UiSelector().text(\"" + text + "\").instance(0));"));
282						break;
283					} else {
284						scrollDown();
285					}
286				}
287			} else {
288				try {
289					if (new WebDriverWait(appiumDriver, 15).until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath))).isDisplayed()) {
290						element = appiumDriver.findElementByXPath(xpath);
291					}
292				} catch (Exception e) {
293					element = scrollByText(text, xpath);
294				}
295			}
296		} catch (Exception e) {
297			e.printStackTrace();
298		}
299	    return element;
300	}
301	
302
303	private String getVersion() {
304		JSONObject sessionObj = null;
305		if(sessionObj == null) {
306			sessionObj = new JSONObject(appiumDriver.getSessionDetails());
307		}
308		String version = sessionObj.optString("platformVersion").trim().split("\\.")[0];
309		return version;
310	}
311	
312	public boolean isElementFound(String text) {
313        try {
314           appiumDriver.findElement(By.xpath(text));
315        } catch(Exception e){
316            return false;
317        }
318        return true;
319    }
320	
321	
322	public MobileElement scrollByText(String text, String xpath) {
323		try {
324			return appiumDriver.findElement(MobileBy.AndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().text(\"" + text + "\").instance(0));"));
325		} catch (Exception e) {
326			WebElement isElementPresence = waitForExpectedElement(appiumDriver, xpath, 60);
327			if (isElementPresence.isDisplayed()) {
328				return appiumDriver.findElementByXPath(xpath);
329			}
330		}
331		return null;
332	}
333	
334	/*************************************** Find element by Id *************************************/
335	// used to finding the element in screen 
336	// scrolls full page for finding the element by ID 
337	protected MobileElement findElementById(String id) {
338		MobileElement element = null;
339		String xpath = id.split("'")[1];
340		try {
341			//element = (MobileElement) appiumDriver.findElementByAccessibilityId(xpath);
342			element = appiumDriver.findElement(MobileBy.AndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0))" +
343	            ".scrollIntoView(new UiSelector().resourceId(\"" + xpath + "\").instance(0))"));
344		} catch (Exception e) {
345			WebElement isElementPresence = waitForExpectedElement(appiumDriver, id, 60);
346			if(isElementPresence.isDisplayed()) {
347			element = appiumDriver.findElement(MobileBy.AndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0))" +
348	            ".scrollIntoView(new UiSelector().resourceId(\"" + xpath + "\").instance(0))"));
349			}
350		}
351		System.out.println("Search Box Name - " + element.getText());
352		return element;
353	}
354	
355	//Only For android password field
356	protected WebElement findElementByPwd(String Pwd, String value) {
357		WebElement PasswordTextInputText = waitForExpectedElement(appiumDriver, Pwd, 60);
358		PasswordTextInputText.sendKeys(value);
359		return PasswordTextInputText;
360	}
361			
362	// wait 60 seconds for finding the element
363	public static WebElement waitForExpectedElement(AppiumDriver<MobileElement> appiumDriver, String locator, long timeOutInSeconds) {
364		WebDriverWait wait = new WebDriverWait(appiumDriver, timeOutInSeconds);
365		appiumDriver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
366		return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(locator)));
367	}
368	
369	
370	
371	/*********************************** ScrollDown (Android/iOS) ***********************************/
372	
373	private void scrollDown() {
374	    //if pressX was zero it didn't work for me
375	    int pressX = appiumDriver.manage().window().getSize().width / 2;
376	    // 4/5 of the screen as the bottom finger-press point
377	    int bottomY = appiumDriver.manage().window().getSize().height * 4/5;
378	    // just non zero point, as it didn't scroll to zero normally
379	    int topY = appiumDriver.manage().window().getSize().height / 8;
380	    //scroll with TouchAction by itself
381	    scroll(pressX, bottomY, pressX, topY);
382	}
383	
384	
385	/*
386	 * Don't forget that it's "natural scroll" where 
387	 * fromY is the point where you press and toY where you release it
388	 */
389	@SuppressWarnings("rawtypes")
390	private void scroll(int fromX, int fromY, int toX, int toY) {
391	    TouchAction touchAction = new TouchAction(appiumDriver);
392	    touchAction.longPress(PointOption.point(fromX, fromY)).moveTo(PointOption.point(toX, toY)).release().perform();
393	}
394
395	/************************************** Reports ******************************************/
396	
397	// These methods used to write the extent reports and logger
398	public void testPass(String message, ExtentTest test, Logger logger) {
399		test.log(LogStatus.PASS, message);
400		logger.info(message);
401	}
402
403	public void testInfo(String message, ExtentTest test, Logger logger) {
404		test.log(LogStatus.INFO, message);
405		logger.info(message);
406	}
407
408	public void testFail(String message, ExtentTest test, Logger logger, AppiumDriver<MobileElement> mobileDriver) {
409		test.log(LogStatus.FAIL, message);
410		logger.error(message);
411		Utilities.setMobilePlatform();
412		test.log(LogStatus.INFO, "Screenshot Taken : " + Utilities.captureScreenshot(mobileDriver, message + " is Failed"));
413	}
414
415	// ScreenName Header for Reports
416	public static void testLogHeader(ExtentTest test ,String data) {
417		test.log(LogStatus.INFO, "<b style = 'background-color: #ffffff; color : #ff8f00 ; font-size : 18px' >"+ data + "</b>");
418	}
419	
420	
421	/*********************************** Find the Client OS ****************************************/
422	
423	private static String OS = System.getProperty("os.name").toLowerCase();
424	private static boolean isMac() {
425		return (OS.indexOf("mac") >= 0);
426	}
427	
428	
429	
430	
431//	@SuppressWarnings("rawtypes")
432//	public void swipingHorizontal(String xpath) throws InterruptedException {
433//		  //Get the size of screen.
434//		  int size = 0;
435//
436//		  //Find swipe x points from screen's with and height.
437//		  //Find x1 point which is at right side of screen.
438//		  int x1 = (int) (appiumDriver.manage().window().getSize().width * 0.70);
439//		  //Find x2 point which is at left side of screen.
440//		  int x2 = (int) (appiumDriver.manage().window().getSize().width * 0.30);
441//		  
442//		  //Create object of TouchAction class.
443//		  TouchAction action = new TouchAction(appiumDriver);
444//		  
445//		  //Find element to swipe from right to left.
446//		 // MobileElement ele1 =  appiumDriver.findElementById(xpath);  
447//		  //Create swipe action chain and perform horizontal(right to left) swipe.
448//		  //Here swipe to point x1 Is at left side of screen. So It will swipe element from right to left.
449//		 // action.longPress(LongPressOptions.longPressOptions().withElement(ElementOption.element(ele1))).moveTo(PointOption.point(x1,580)).release().perform();
450// 
451//		  //Find element to swipe from left to right.
452//		  MobileElement ele2 =  appiumDriver.findElementById(xpath);
453//		  //Create swipe action chain and perform horizontal(left to right) swipe.
454//		  //Here swipe to point x2 Is at right side of screen. So It will swipe element from left to right.
455//		  
456//		  action.longPress(LongPressOptions.longPressOptions().withElement(ElementOption.element(ele2))).moveTo(PointOption.point(x2,580)).release().perform();
457//	}
458//	
459//	public  void swipeLeft(String xpath) {
460//		Point[] points = getXYtoHSwipe();
461//		 MobileElement ele2 =  appiumDriver.findElementByXPath(xpath);
462//		 int x =  ele2.getLocation().getX();
463//		 int y =  ele2.getLocation().getY();
464//
465//		new TouchAction(appiumDriver).longPress(LongPressOptions.longPressOptions().withPosition(PointOption.point(x,y))).moveTo(PointOption.point(points[1].x, points[1].y)).release().perform();
466//	}
467//	
468//	/**
469//	 *
470//	 * @return start and end points for horizontal(left-right) swipe
471//	 */
472//	private  Point[] getXYtoHSwipe() {
473//		// Get screen size.
474//		Dimension size = appiumDriver.manage().window().getSize();
475//
476//		// Find starting point x which is at right side of screen.
477//		int startx = (int) (size.width * 0.70);
478//		// Find ending point x which is at left side of screen.
479//		int endx = (int) (size.width * 0.30);
480//		// Find y which is in middle of screen height.
481//		int startEndy = size.height / 2;
482//
483//		return new Point[] { new Point(startx, startEndy), new Point(endx, startEndy) };
484//	}
485//	
486//
487//	/**
488//	 * Swipe from Left to Right
489//	 */
490//	public  void swipeRight(String xpath) {
491//		Point[] points = getXYtoHSwipe();
492//		 MobileElement ele2 =  appiumDriver.findElementByXPath(xpath);
493//		 int x =  (int)(ele2.getLocation().getX() * 0.20);
494//		 int y =  (int)(ele2.getLocation().getY() * 0.80);
495//		new TouchAction(appiumDriver).longPress(LongPressOptions.longPressOptions().withPosition(PointOption.point(x,y))).moveTo(PointOption.point(points[0].x, points[0].y)).release().perform();
496//	}
497//	
498	
499}
500
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)