Best io.appium code snippet using io.appium.java_client.TouchAction
apprunner.java
Source:apprunner.java  
...17import io.appium.java_client.touch.offset.ElementOption;18import org.openqa.selenium.By;19import io.appium.java_client.AppiumDriver;20import io.appium.java_client.MobileElement;21import io.appium.java_client.TouchAction;22//import io.appium.java_client.TouchAction;23import io.appium.java_client.android.AndroidDriver;24import io.appium.java_client.pagefactory.AndroidFindBy;25import io.appium.java_client.service.local.AppiumDriverLocalService;26import static io.appium.java_client.touch.TapOptions.tapOptions;27import static io.appium.java_client.touch.offset.ElementOption.element;28import static io.appium.java_client.touch.LongPressOptions.longPressOptions;29import static io.appium.java_client.touch.offset.PointOption.point;30import static io.appium.java_client.touch.WaitOptions.waitOptions;31import static java.time.Duration.ofMillis;32public class apprunner {33	public AppiumDriver<MobileElement> wd = null;34	static AppiumDriverLocalService service;35	36	@BeforeSuite37	public void startAppium() {38		service = AppiumDriverLocalService.buildDefaultService();39		service.start();40	}41	42	@BeforeTest43	public void setup() {44		DesiredCapabilities capabilities = new DesiredCapabilities();45		capabilities.setCapability("platformName", "Android");46		capabilities.setCapability("platformVersion", "8.1");47		capabilities.setCapability("appPackage", "io.appium.android.apis");48		capabilities.setCapability("appActivity", ".ApiDemos");49		capabilities.setCapability("deviceName", "Pixel 2");50		capabilities.setCapability("app", "C:\\Users\\rahulmishra01\\Downloads\\ApiDemos-debug.apk");51		52		try {53			wd = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"),capabilities);54		}catch(Exception e) {55			e.printStackTrace();56		}57	}58	59	public MobileElement waitForElement(MobileElement element) {60		try {61			WebDriverWait wait=new WebDriverWait(wd, 60);62		} catch(Exception e) {63			System.out.println(element+"is not displayed on the web page");64		}65		return element;66		67	}68	69	//@Test70	/*public void apidemoapp() throws Throwable {71		wd.findElementByXPath("//android.widget.TextView[@content-desc=\"Graphics\"]").click();72		Thread.sleep(5000);73		74		//Tap functionality75		76		TouchAction touch=new TouchAction(wd);77		MobileElement Element=wd.findElementByAccessibilityId("Arcs");78		touch.tap(tapOptions().withElement(element(Element))).release().perform();79		Thread.sleep(5000);80		81		//Drag and Drop82		/*TouchAction touch=new TouchAction(wd);83		MobileElement Element1=wd.findElementByAccessibilityId("ColorFilters");84		MobileElement Element2=wd.findElementByAccessibilityId("Arcs");85		touch.longPress(longPressOptions().withElement(element(Element1))).moveTo(element(Element2)).release().perform();86		Thread.sleep(5000);87		*/88		89		//swipe90		/*verticalswipeByPercentage(0.70,0.10,0.50);91	}92	93	public void verticalswipeByPercentage(double startpercentage, double endpercentage, double anchorpercentage) throws Throwable {94		Dimension size = wd.manage().window().getSize();95		int anchor = (int)(size.width * anchorpercentage);96		int startpoint = (int)(size.height * startpercentage);97		int endpoint = (int)(size.height * endpercentage);98		new TouchAction(wd).press(point(anchor,startpoint)).waitAction(waitOptions(ofMillis(1000))).moveTo(point(anchor,endpoint)).release().perform();99		Thread.sleep(5000);100		101		102	}*/103	104	/*105	@AndroidFindBy(xpath = "//*[@text='Animation']")106    public MobileElement lnkAnimation;107    @AndroidFindBy(xpath = "//*[@text='App']")108    public MobileElement lnkApp;109    110    @AndroidFindBy(xpath = "//*[@text='Animation/Default Layout Animations']")111    public MobileElement lbldefaultlayoutanimations;112    @AndroidFindBy(xpath = "//*[@text='ADD BUTTON']")113    public MobileElement btnAddButton;114	public boolean verifyAnimationicon() {115        boolean displayAnimationflag = false;116        try{117            lnkAnimation.isDisplayed();118            displayAnimationflag = true;119        } catch (Exception e) {120            System.out.println(e + ": Animation icon is not displayed!!");121        }122        return displayAnimationflag;123    }124	125	public boolean verifyDefaultLaoyoutAnimationScreen() {126        boolean defaultanimationscreenflag = false;127        try{128            lbldefaultlayoutanimations.isDisplayed();129            defaultanimationscreenflag = true;130        } catch (Exception e) {131            System.out.println(e + ": Default Layout Animations screen is not displayed!!");132        }133        return defaultanimationscreenflag;134    }135	136	/* public void iVerifyButtonDisplay(int buttons) {137	        Assert.assertEquals(getbuttons(), buttons, "The no. of buttons displayed is invalid!!");138	        //Log.info("The button " + buttons + " is displayed successfully!!");139	    }*/140	141	   /* public int getbuttons() {142	        return wd.findElements(By.xpath("//*[@resource-id='io.appium.android.apis:id/gridContainer']//android.widget.Button")).size();143	    }144	    */145	146	147	@Test148	public void animation_screen() {149		150		//Assert.assertTrue(verifyAnimationicon(), "Animation icon is not displayed!!");151		152		new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.xpath("//android.widget.TextView[@content-desc=\"Animation\"]"))))).perform();153		154		//Assert.assertTrue(verifyDefaultLaoyoutAnimationScreen(), "Default Layout Animations screen is not displayed!!");155		156		new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.xpath("//android.widget.TextView[@content-desc=\"Default Layout Animations\"]"))))).perform();157		158		new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.xpath("//android.widget.Button[@content-desc=\"Add Button\"]"))))).perform();159		160		new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.id("io.appium.android.apis:id/addNewButton"))))).perform();161		162		new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.xpath("//android.widget.Button[@content-desc=\"Add Button\"]"))))).perform();163		164		new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.id("io.appium.android.apis:id/addNewButton"))))).perform();165	    166		167		//Assert.assertEquals(getbuttons(), buttons, "The no. of buttons displayed is invalid!!");168		169		wd.quit();170	171	}172	173	@Test174	public void content_screen() {175		176		177		new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.xpath("//android.widget.TextView[@content-desc=\"Content\"]"))))).perform();178		179		//new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.id("io.appium.android.apis:id/addNewButton"))))).perform();180		181		new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.xpath("//android.widget.TextView[@content-desc=\"Resources\"]"))))).perform();182		183		new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.xpath("//android.widget.TextView[@content-desc=\"Layout Reference\"]"))))).perform();184		185		wd.quit();186		187	}188	189	//@Test190	public void content_screen_asset() {191		new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.xpath("//android.widget.TextView[@content-desc=\"Content\"]"))))).perform();192		193		new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.xpath("//android.widget.TextView[@content-desc=\"Assets\"]"))))).perform();194		195		new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.xpath("//android.widget.TextView[@content-desc=\"Read Asset\"]"))))).perform();196		197		wd.quit();198	}199	200	201	@Test202	public void preference_screen() {203		new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.xpath("//android.widget.TextView[@content-desc=\"Preference\"]"))))).perform();204		205		new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.xpath("//android.widget.TextView[@content-desc=\"4. Default values\"]"))))).perform();206	207		new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.xpath("//android.widget.TextView[@content-desc=\"Preference\"]"))))).perform();208		209		210		//new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.xpath("//*[@text='Checkbox preference']"))))).perform();211		212		//new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.id("io.appium.android.apis:id/checkbox"))))).perform();213		214		215		216		//Edit Preferences217		218		//new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.xpath("//*[@text='Edit text preference']"))))).perform();219		220		//new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.xpath("//android.widget.TextView[@content-desc=\"Edit Text Preference\"]"))))).perform();221		222		223		//new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.id("io.appium.android.apis:id/edit"))))).perform();224		225		//new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.xpath("//android.widget.EditText[@text=\"Default value\"]"))))).clear();226		//new TouchAction(wd).tap(TapOptions.tapOptions().withElement(ElementOption.element((wd).findElement(By.xpath("//android.widget.EditText[@text=\"Default value\"]"))))).perform();227		228		//wd.findElement(By.id("io.appium.android.apis:id/edit")).sendKeys("Horse");229		230	231	}232	233	/*@AfterTest234	public void stopappium(){235		wd.quit();236		}237		*/238	239	240	@AfterSuite...Utilities.java
Source:Utilities.java  
1package Utilities;2import com.google.common.collect.ImmutableMap;3import io.appium.java_client.MobileElement;4import io.appium.java_client.TouchAction;5import io.appium.java_client.android.AndroidDriver;6import io.appium.java_client.android.AndroidElement;7import io.appium.java_client.ios.IOSElement;8import io.appium.java_client.remote.MobileCapabilityType;9import io.appium.java_client.touch.LongPressOptions;10import io.appium.java_client.touch.TapOptions;11import io.appium.java_client.touch.WaitOptions;12import io.appium.java_client.touch.offset.ElementOption;13import io.appium.java_client.touch.offset.PointOption;14import io.cucumber.core.gherkin.Step;15import io.appium.java_client.TouchAction.*;16import static io.appium.java_client.touch.TapOptions.tapOptions;17import static io.appium.java_client.touch.offset.ElementOption.element;18import static io.appium.java_client.touch.LongPressOptions.longPressOptions;19import static java.time.Duration.ofSeconds;20import org.junit.Assert;21import org.openqa.selenium.Dimension;22import org.openqa.selenium.WebElement;23import org.openqa.selenium.remote.DesiredCapabilities;24import org.openqa.selenium.support.ui.ExpectedConditions;25import org.openqa.selenium.support.ui.WebDriverWait;26import stepDefnition.StepDefinitions;27import java.io.FileInputStream;28import java.io.FileNotFoundException;29import java.io.IOException;30import java.net.MalformedURLException;31import java.net.URL;32import java.time.Duration;33import java.util.HashMap;34import java.util.Properties;35import java.util.Set;36import java.util.concurrent.TimeUnit;37public class Utilities {38    public static Properties properties;39    public  void tapOnElement(AndroidElement myElement) {40        TouchAction touchAction=new TouchAction(StepDefinitions.driver);41//        touchAction.tap(tapOptions().withElement(element(myElement))).perform();42//        touchAction.tap(TapOptions.tapOptions().withElement(element(myElement)));43        touchAction.tap(TapOptions.tapOptions().withElement(element(myElement))).perform();44    }45    public void longPressOnElement(AndroidElement myElement){46        TouchAction touchAction=new TouchAction(StepDefinitions.driver);47        touchAction.longPress(longPressOptions().withElement(element(myElement)).withDuration(ofSeconds(2))).release().perform();48    }49    public void doubleTapOnElement(AndroidElement myElement){50        TouchAction touchAction=new TouchAction(StepDefinitions.driver);51        touchAction.tap(TapOptions.tapOptions().withElement(element(myElement))).release().perform().52                tap(TapOptions.tapOptions().withElement(element(myElement))).release().perform();53    }54    public void fnEnterTextValue(WebElement myElement,String myValue){55        myElement.sendKeys(myValue);56    }57    public void DragAndDropElement(AndroidElement fromElement,AndroidElement toElement){58        TouchAction touchAction=new TouchAction(StepDefinitions.driver);59        touchAction.longPress(longPressOptions().withElement(element(fromElement))).60                moveTo(element(toElement)).release().perform();61    }62    public void dragFirstElementToSecondElement(AndroidElement fromElement, AndroidElement toElement) {63        TouchAction touchAction=new TouchAction(StepDefinitions.driver);64        touchAction.longPress(LongPressOptions.longPressOptions().withElement(element(fromElement)))65                .moveTo(element(toElement)).release().perform();66    }67    public void userLaunchesChromeBrowserInMobile() throws MalformedURLException {68        DesiredCapabilities capabilities=new DesiredCapabilities();69        capabilities.setCapability(MobileCapabilityType.DEVICE_NAME,"Galaxy S9+")  ;70        capabilities.setCapability(MobileCapabilityType.UDID,"42345a3836313098");71        capabilities.setCapability(MobileCapabilityType.BROWSER_NAME,"Chrome");72        capabilities.setCapability("appium:chromeOptions", ImmutableMap.of("w3c", false));73        AndroidDriver<AndroidElement> driver=new AndroidDriver<>(new URL("http://0.0.0.0:4723/wd/hub"),capabilities);74//        driver=new AndroidDriver<>(new URL("http://0.0.0.0:4723/wd/hub"),capabilities);75        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);76        driver.get("http://www.timesofindia.com");77    }78    public void userSelectsFromDropdown(String arg0) {79        AndroidElement myelement=StepDefinitions.driver.findElementById("com.androidsample.generalstore:id/spinnerCountry");80        tapOnElement(myelement);81    }82    public void scrollTillAnElementWithTextIsDisplayed(String arg0) {83     AndroidElement expectedElement = null;84     Dimension size=StepDefinitions.driver.manage().window().getSize();85        //x position set to mid-screen horizontally86        int width = size.width / 2;87        //Starting y location set to 80% of the height (near bottom)88        int startPoint = (int) (size.getHeight() * 0.80);89        //Ending y location set to 20% of the height (near top)90        int endPoint = (int) (size.getHeight() * 0.30);91     TouchAction touchAction=new TouchAction(StepDefinitions.driver);92         do {93             try{94                 expectedElement=StepDefinitions.driver.findElementByXPath("//*[@text='"+arg0+"']");95                if(expectedElement.isDisplayed()){96                    tapOnElement(expectedElement);97                    break;98                }99             }catch(Exception e){100                 touchAction.press(PointOption.point(width,startPoint)).101                         waitAction(WaitOptions.waitOptions(Duration.ofSeconds(2))).102                         moveTo(PointOption.point(width,endPoint)).103                         release().104                         perform();105                 continue;106             }107         }while (true);108    }109    public void switchNativeToWeb() throws InterruptedException {110        Thread.sleep(10000);111        Set<String> contextNames = StepDefinitions.driver.getContextHandles();112        for (String contextName : contextNames) {113            System.out.println(contextName); //prints out something like NATIVE_APP \n WEBVIEW_1114        }115        StepDefinitions.driver.context((String) contextNames.toArray()[1]);116//        StepDefinitions.driver.context("NATIVE_APP");117    }118    public void switchWebToNative() {119        StepDefinitions.driver.context("NATIVE_APP");120    }121    public void tapOnElementUpdate(MobileElement myelement) {122    }123    public void tapOnIOSElement(WebElement activity_indicators) throws InterruptedException {124        Thread.sleep(2000);125        TouchAction touchAction=new TouchAction(StepDefinitions.IOSDriver);126        touchAction.tap(TapOptions.tapOptions().withElement(ElementOption.element(activity_indicators))).release().perform();127    }128    public void LoadProperiesFile() throws IOException {129        FileInputStream fis=new FileInputStream("config.properties");130        Utilities.properties=new Properties();131        Utilities.properties.load(fis);132        Utilities.properties.getProperty("iOSAppPath");133        System.out.println("IOSFile Path is :-"+Utilities.properties.getProperty("iOSAppPath"));134    }135    public void enterTextInIOSEditBox(IOSElement elementByXPath, String sample) {136        elementByXPath.sendKeys(sample);137        StepDefinitions.IOSDriver.hideKeyboard();138    }139    public void fnVerifyExpectedLabelFromIOSElement(IOSElement iOSElement,String sExpectedValue){...ChromeTest.java
Source:ChromeTest.java  
1import org.testng.annotations.Test;2import io.appium.java_client.AppiumDriver;3import io.appium.java_client.MobileElement;4import io.appium.java_client.MultiTouchAction;5import io.appium.java_client.TouchAction;6import io.appium.java_client.android.AndroidDriver;7import io.appium.java_client.android.NetworkSpeed;8import io.appium.java_client.touch.LongPressOptions;9import io.appium.java_client.touch.TapOptions;10import net.bytebuddy.description.NamedElement.WithOptionalName;11import org.testng.annotations.BeforeMethod;12import static org.testng.Assert.assertEquals;13import java.util.List;14import java.net.MalformedURLException;15import java.net.URL;16import java.time.Duration;17import java.util.ArrayList;18import java.util.concurrent.TimeUnit;19import org.openqa.selenium.By;20import org.openqa.selenium.WebElement;21import org.openqa.selenium.remote.DesiredCapabilities;22import org.springframework.util.Assert;23import org.testng.annotations.AfterMethod;24import static io.appium.java_client.touch.TapOptions.tapOptions;25import static io.appium.java_client.touch.LongPressOptions.longPressOptions;26import static io.appium.java_client.touch.WaitOptions.waitOptions;27import static io.appium.java_client.touch.offset.ElementOption.element;28import static io.appium.java_client.touch.offset.PointOption.point;29import static java.time.Duration.ofMillis;30import static java.time.Duration.ofSeconds;31public class ChromeTest {32	33  AndroidDriver<MobileElement> driver; 34  35  @BeforeMethod36  public void beforeMethod() throws MalformedURLException {37	  DesiredCapabilities cap = new DesiredCapabilities();38	  cap.setCapability("deviceName", "Android Emulator");39	  cap.setCapability("uid", "emulator-5554");40	  cap.setCapability("platformName", "Android");41	  cap.setCapability("platformVersion", "11.0");42	  cap.setCapability("appPackage", "com.android.settings");43	  cap.setCapability("appActivity", "com.android.settings.Settings");44	  45	  URL url = new URL("http://127.0.0.1:4723/wd/hub");46	  driver = new AndroidDriver<MobileElement>(url, cap);47	  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);48	  System.out.println("Started");49  }50  @AfterMethod51  public void afterMethod() {52	  System.out.println("End");53	  driver.quit();54  }55  @Test(enabled=false)56  public void Test1() throws InterruptedException {57	  System.out.println("Running......");58	  driver.findElement(By.id("com.android.dialer:id/fab")).click();59	  driver.findElement(By.id("com.android.dialer:id/one")).click();60	  driver.findElement(By.id("com.android.dialer:id/one")).click();61	  driver.findElement(By.id("com.android.dialer:id/two")).click();62	  String num = driver.findElement(By.id("com.android.dialer:id/digits")).getText();63	  System.out.println(num);64	  assertEquals(num, "112");65	  Thread.sleep(10000);	66  }67  68  @Test(enabled=false)69  public void Test2() throws InterruptedException {70	  System.out.println("Running......");71	  driver.findElement(By.id("com.android.dialer:id/main_options_menu_button")).click();72	  driver.openNotifications();73	  List<MobileElement> ele = driver.findElements(By.id("android:id/notification_header"));74	  System.out.println(ele.size());75      for (MobileElement mobileElement : ele) {  76    	  List<MobileElement> child = mobileElement.findElements(By.xpath("//android.widget.TextView"));77		  System.out.println("Child: "+child.size());78    	  for(MobileElement chl : child) {79			  if(chl.getText().equals("Settings")) {80					System.out.println("Notification found");81				}82		  }83	}84  }85  86  @Test(enabled=false)87  public void Test3() {88	  driver.installApp("C:\\Users\\Darshan Naik\\Downloads\\BMI Calculator Body Fat Percentage Ideal Weight_v4.3.1_apkpure.com.apk");89      driver.removeApp("com.bmi.bmr.body.fat.calculator");90  }91  92  @Test(enabled=false)93  public void Test4() {94	  System.out.println("*--*--*-- Current screen orientation Is : " + driver.getOrientation());95	  System.out.println("*--*--*-- Changing screen Orientation to LANDSCAPE.");96	  //Changing screen Orientation to LANDSCAPE.97	  driver.rotate(org.openqa.selenium.ScreenOrientation.LANDSCAPE);98	  //Get and print screen orientation after changing It.99	  System.out.println("*--*--*-- Now screen orientation Is : "+ driver.getOrientation());100  }101  102  @Test(enabled=false)103  public void Test5() {104	  driver.setNetworkSpeed(NetworkSpeed.LTE);105	  /*106	  //Unfortunately, at the moment Appium does not support the Selenium network connection API for Windows.107	  // set airplane mode108	  driver.setNetworkConnection(1);109	  // set wifi only110	  driver.setNetworkConnection(2);111	  // set data only112	  driver.setNetworkConnection(4);113	  // set wifi and data114	  driver.setNetworkConnection(6);115	  */116  }117  118  @Test(enabled=false)119  public void Test6() throws InterruptedException {120	  List<MobileElement> ele = driver.findElements(By.xpath("//androidx.recyclerview.widget.RecyclerView"));121	  MobileElement mb = ele.get(1);122	  List<MobileElement> ele2 = mb.findElements(By.xpath("//android.widget.LinearLayout"));123	  System.out.println(ele2.size());124	  for (MobileElement mobileElement : ele2) {125		MobileElement m = mobileElement.findElement(By.id("android:id/title"));126		System.out.println(m.getText());127		128	}129	  130  }131  @Test132  public void Test7() throws InterruptedException {133	  MobileElement ele = driver.findElement(By.xpath("/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.view.ViewGroup/android.widget.ScrollView/android.widget.LinearLayout/android.widget.FrameLayout[2]/android.widget.LinearLayout/android.widget.FrameLayout/androidx.recyclerview.widget.RecyclerView/android.widget.LinearLayout[1]"));134	  135	  //Tap using element136	  TouchAction ac1 = new TouchAction(driver);137	  ac1.tap(tapOptions().withElement(element(ele)))138	    .waitAction(waitOptions(Duration.ofSeconds(2)))139	    .perform();140	  141	  //tap using coordinates142	  TouchAction ac2 = new TouchAction(driver);143	  ac2.tap(point(500, 700))144	  	.perform();145	  Thread.sleep(10000);146	  147	  //press using element148	  TouchAction ac3 = new TouchAction(driver);149	  ac3.press(element(ele))150	  	 .waitAction(waitOptions(Duration.ofSeconds(2)))151	  	 .release()152	  	 .perform();153	  Thread.sleep(1000);154	  155	  //press using coordinates156	  TouchAction ac4 = new TouchAction(driver);157	  ac4.press(point(500, 700))158	    .waitAction(waitOptions(Duration.ofSeconds(2)))159	     .release()160	    .perform();161	  162	  //Swipe vertically163	  TouchAction ac5 = new TouchAction(driver);164	  ac5.press(point(540, 800))165	     .waitAction(waitOptions(ofMillis(1000)))166	     .moveTo(point(540, 400))167	     .release()168	     .perform();169	  Thread.sleep(10000);170	  171	  //Multi touch172	  TouchAction ac6 = new TouchAction(driver);173	  ac6.press(point(500, 700))174	    .waitAction(waitOptions(ofMillis(1000)))175	    .release()176	    .perform();177	  178	  new MultiTouchAction(driver)179	  	.add(ac6)180	  	.perform();181	  182	  //Long press183	  TouchAction action = new TouchAction(driver);184	  action.longPress(longPressOptions().withElement(element(ele)))185	  		.waitAction(waitOptions(ofMillis(1000)))186	  		.release()187	  		.perform();188	  189  }190  191}...AppiumUtils.java
Source:AppiumUtils.java  
1package com.appiumair.util;2import io.appium.java_client.PerformsTouchActions;3import io.appium.java_client.TouchAction;4import io.appium.java_client.android.AndroidBatteryInfo;5import io.appium.java_client.android.AndroidDriver;6import io.appium.java_client.touch.WaitOptions;7import io.appium.java_client.touch.offset.PointOption;8import org.openqa.selenium.WebDriver;9import java.text.DecimalFormat;10import java.text.NumberFormat;11import java.time.Duration;12import java.util.ArrayList;13import java.util.HashMap;14import java.util.List;15import java.util.Map;16/**17 * Appiumåç§æä½å·¥å
·ç±»18 */19public class AppiumUtils {20    public AppiumUtils() {}21    /**22     * @param driver23     * @module 䏿»æä½24     */25    public static void swipeUp(WebDriver driver) {26        int width = driver.manage().window().getSize().width;27        int height = driver.manage().window().getSize().height;28        TouchAction touchAction = new TouchAction((PerformsTouchActions) driver);29        PointOption pointOption = PointOption.point(width / 2, height * 3 / 4);30        touchAction.press(pointOption).waitAction(WaitOptions.waitOptions(Duration.ofMillis(500))).moveTo(PointOption.point(width / 2, height / 4)).release().perform();31    }32    /**33     * @param driver34     * @module 䏿»æä½35     */36    public static void swipeDown(WebDriver driver) {37        int width = driver.manage().window().getSize().width;38        int height = driver.manage().window().getSize().height;39        TouchAction touchAction = new TouchAction((PerformsTouchActions) driver);40        PointOption pointOption = PointOption.point(width / 2, height / 4);41        touchAction.press(pointOption).waitAction(WaitOptions.waitOptions(Duration.ofMillis(500))).moveTo(PointOption.point(width / 2, height * 3 / 4)).release().perform();42    }43    /**44     * @param driver45     * @module å·¦æ»æä½46     */47    public static void swipeLeft(WebDriver driver) {48        int width = driver.manage().window().getSize().width;49        int height = driver.manage().window().getSize().height;50        TouchAction touchAction = new TouchAction((PerformsTouchActions) driver);51        PointOption pointOption = PointOption.point(width * 4 / 5, height / 2);52        touchAction.press(pointOption).waitAction(WaitOptions.waitOptions(Duration.ofMillis(500))).moveTo(PointOption.point(width / 5, height / 2)).release().perform();53    }54    /**55     * @param driver56     * @module 峿»æä½57     */58    public static void swipeRight(WebDriver driver) {59        int width = driver.manage().window().getSize().width;60        int height = driver.manage().window().getSize().height;61        TouchAction touchAction = new TouchAction((PerformsTouchActions) driver);62        PointOption pointOption = PointOption.point(width / 5, height / 4);63        touchAction.press(pointOption).waitAction(WaitOptions.waitOptions(Duration.ofMillis(500))).moveTo(PointOption.point(width * 4 / 5, height / 2)).release().perform();64    }65    /**66     * æ§è¡æµè¯åï¼æ£æ¥å设å¤çµéæ
åµï¼çµéä¸è¶³ååºè¦å67     * @param driver68     * @return çµéç¶ææ¯å¦å
许å¯ç»§ç»æ§è¡69     */70    public static Double checkBattery(AndroidDriver driver) {71        String message = "";72        double batteryLevel = driver.getBatteryInfo().getLevel();73        String batteryState = driver.getBatteryInfo().getState().name();74        return batteryLevel;75    }...SafetyScoreTest.java
Source:SafetyScoreTest.java  
...3import org.junit.Test;4import org.junit.runner.RunWith;5import org.openqa.selenium.remote.DesiredCapabilities;6import io.appium.java_client.MobileElement;7import io.appium.java_client.TouchAction;8import io.appium.java_client.android.AndroidDriver;9import io.appium.java_client.android.AndroidElement;10import io.appium.java_client.remote.MobileCapabilityType;11import static io.appium.java_client.touch.offset.PointOption.point;12@RunWith(AndroidJUnit4ClassRunner.class)13public class SafetyScoreTest {14    @Test15    public void testSafetyScore(){16        DesiredCapabilities dc = new DesiredCapabilities();17        dc.setCapability(MobileCapabilityType.DEVICE_NAME, "emulator-5554");18        dc.setCapability(MobileCapabilityType.PLATFORM_NAME, "android");19        dc.setCapability("appPackage", "com.example.locationtest");20        dc.setCapability("appActivity", ".MainActivity");21        AndroidDriver<AndroidElement> driver = new AndroidDriver<AndroidElement>(dc);22        MobileElement el1 = (MobileElement) driver.findElementById("com.example.locationtest:id/maps_button");23        el1.click();24        MobileElement el2 = (MobileElement) driver.findElementById("com.android.permissioncontroller:id/permission_allow_foreground_only_button");25        el2.click();26        MobileElement el3 = (MobileElement) driver.findElementById("com.example.locationtest:id/maps_button");27        el3.click();28        MobileElement el7 = (MobileElement) driver.findElementByAccessibilityId("Incident 6 (1). ");29        el7.click();30        MobileElement el8 = (MobileElement) driver.findElementByAccessibilityId("Zoom in");31        el8.click();32        (new TouchAction(driver)).tap(point(181, 1114)).perform();33        MobileElement el9 = (MobileElement) driver.findElementById("com.example.locationtest:id/getSafetyScoreButton");34        el9.click();35        (new TouchAction(driver)).tap(point(450, 1070)).perform();36        el9.click();37        (new TouchAction(driver)).tap(point(181, 1114)).perform();38        el9.click();39        (new TouchAction(driver)).tap(point(450, 1070)).perform();40        el9.click();41        (new TouchAction(driver)).tap(point(181, 1114)).perform();42        el9.click();43        (new TouchAction(driver)).tap(point(450, 1070)).perform();44        el9.click();45        (new TouchAction(driver)).tap(point(181, 1114)).perform();46        el9.click();47        (new TouchAction(driver)).tap(point(450, 1070)).perform();48        el9.click();49        (new TouchAction(driver)).tap(point(181, 1114)).perform();50        el9.click();51        (new TouchAction(driver)).tap(point(450, 1070)).perform();52        el9.click();53    }54}...commonbase.java
Source:commonbase.java  
...7import org.openqa.selenium.Dimension;8import org.openqa.selenium.support.PageFactory;9import io.appium.java_client.AppiumDriver;10import io.appium.java_client.MobileElement;11import io.appium.java_client.TouchAction;12import io.appium.java_client.pagefactory.AppiumFieldDecorator;13/////////14/////////////////////////////////////15// common tap & swipe functionality for the screens16////////////////////17public class commonbase {18	public static AppiumDriver<MobileElement> ad = null;19	public commonbase(AppiumDriver<MobileElement> ad) {20		this.ad = ad;21		PageFactory.initElements(new AppiumFieldDecorator(ad), this);22	}23	// tap functionality24	public void tap(MobileElement Element) {25		TouchAction touch = new TouchAction(ad);26		touch.tap(tapOptions().withElement(element(Element))).release().perform();27	}28	29public static void verticalSwipeByElement(MobileElement englishMedium, MobileElement fresherExp) {30		31		int startX = englishMedium.getLocation().getX() + (englishMedium.getSize().getWidth() / 2);32		int startY = englishMedium.getLocation().getY() + (englishMedium.getSize().getHeight() / 2);33		int endX = fresherExp.getLocation().getX() + (fresherExp.getSize().getWidth() / 2);34		int endY = fresherExp.getLocation().getY() + (fresherExp.getSize().getHeight() / 2);35		36		new TouchAction(ad).press(point(startX, startY)).waitAction(waitOptions(ofMillis(1000)))37				.moveTo(point(endX, endY)).release().perform();38	}39	// vertical swipe functionality40	public void vericalSwipeByPercentage(double startPercentage, double endPercentage, double anchorPercentage) {41		Dimension size = ad.manage().window().getSize();42		int anchor = (int) (size.width * anchorPercentage);43		int startPoint = (int) (size.height * startPercentage);44		int endPoint = (int) (size.width * endPercentage);45		new TouchAction(ad).press(point(anchor, startPoint)).waitAction(waitOptions(ofMillis(1000)))46				.moveTo(point(anchor, endPoint)).release().perform();47	}48}...swipedemo.java
Source:swipedemo.java  
1import java.net.MalformedURLException;23import org.openqa.selenium.WebElement;45import io.appium.java_client.TouchAction;6import io.appium.java_client.android.AndroidDriver;7import io.appium.java_client.android.AndroidElement;8import static io.appium.java_client.touch.TapOptions.tapOptions;9import static io.appium.java_client.touch.LongPressOptions.longPressOptions;10import static io.appium.java_client.touch.offset.ElementOption.element;11import static java.time.Duration.ofSeconds;121314public class swipedemo extends base {1516	public static void main(String[] args) throws MalformedURLException {17		// TODO Auto-generated method stub18		19		AndroidDriver<AndroidElement> driver = Capabilities();20		driver.findElementByAndroidUIAutomator("text(\"Views\")").click();21		driver.findElementByAndroidUIAutomator("text(\"Date Widgets\")").click();22		driver.findElementByAndroidUIAutomator("text(\"2. Inline\")").click();23		driver.findElementByXPath("//*[@content-desc = '9']").click();24		TouchAction t = new TouchAction(driver);25		WebElement first = driver.findElementByXPath("//*[@content-desc = '15']");26		WebElement second = driver.findElementByXPath("//*[@content-desc = '45']");27		t.longPress(longPressOptions().withElement(element(first)).withDuration(ofSeconds(2))).moveTo(element(second)).release().perform();28		29	}3031}
...DragDrop.java
Source:DragDrop.java  
1import java.net.MalformedURLException;23import org.openqa.selenium.WebElement;45import io.appium.java_client.TouchAction;6import io.appium.java_client.android.AndroidDriver;7import io.appium.java_client.android.AndroidElement;8import static io.appium.java_client.touch.TapOptions.tapOptions;9import static io.appium.java_client.touch.LongPressOptions.longPressOptions;10import static io.appium.java_client.touch.offset.ElementOption.element;11import static java.time.Duration.ofSeconds;1213public class DragDrop extends base {1415	public static void main(String[] args) throws MalformedURLException {16		// TODO Auto-generated method stub17		18		AndroidDriver<AndroidElement> driver = Capabilities();19		driver.findElementByAndroidUIAutomator("text(\"Views\")").click();20		driver.findElementByAndroidUIAutomator("text(\"Drag and Drop\")").click();21		WebElement source = driver.findElementsByClassName("android.view.View").get(0);22		WebElement destination = driver.findElementsByClassName("android.view.View").get(0);23		TouchAction t = new TouchAction(driver);24		25		t.longPress(element(source)).moveTo(element(destination)).release().perform();26		27	}2829}
...TouchAction
Using AI Code Generation
1package appium;2import java.net.MalformedURLException;3import java.net.URL;4import java.util.concurrent.TimeUnit;5import org.openqa.selenium.By;6import org.openqa.selenium.WebDriver;7import org.openqa.selenium.WebElement;8import org.openqa.selenium.remote.DesiredCapabilities;9import org.openqa.selenium.support.ui.ExpectedConditions;10import org.openqa.selenium.support.ui.WebDriverWait;11import io.appium.java_client.TouchAction;12import io.appium.java_client.android.AndroidDriver;13import io.appium.java_client.android.AndroidElement;14public class TouchActionDemo {15	public static void main(String[] args) throws MalformedURLException {16				DesiredCapabilities caps = new DesiredCapabilities();17				caps.setCapability("deviceName", "Nexus 6 API 24");18				caps.setCapability("platformName", "Android");19				caps.setCapability("platformVersion", "7.0");20				caps.setCapability("appPackage", "com.android.chrome");21				caps.setCapability("appActivity", "com.google.android.apps.chrome.Main");22				caps.setCapability("noReset", "true");23				caps.setCapability("automationName", "uiautomator2");24				caps.setCapability("chromedriverExecutable", "C:\\Users\\Amit\\Downloads\\chromedriver_win32\\chromedriver.exe");TouchAction
Using AI Code Generation
1TouchAction action = new TouchAction(driver);2action.press(100, 100).moveTo(200, 200).release().perform();3MultiTouchAction multiTouch = new MultiTouchAction(driver);4multiTouch.add(action1).add(action2).perform();5from appium.webdriver.common.touch_action import TouchAction6action = TouchAction(driver)7action.press(x=100, y=100).move_to(x=200, y=200).release().perform()8from appium.webdriver.common.multi_action import MultiTouchAction9multiTouch = MultiTouchAction(driver)10multiTouch.add(action1).add(action2).perform()11touch_action.press(x: 100, y: 100).move_to(x: 200, y: 200).release.perform12multi_touch.add(touch_action1).add(touch_action2).perform13var action = new appium.TouchAction(driver);14action.press({x: 100, y: 100}).moveTo({x: 200, y: 200}).release().perform();15var multiTouch = new appium.MultiTouchAction(driver);16multiTouch.add(action1).add(action2).perform();17TouchAction action = new TouchAction(driver);18action.Press(100, 100).MoveTo(200, 200).Release().Perform();19MultiTouchAction multiTouch = new MultiTouchAction(driver);20multiTouch.Add(action1).Add(action2).Perform();TouchAction
Using AI Code Generation
1TouchAction action = new TouchAction(driver);2action.press(x,y).moveTo(x1,y1).release().perform();3MultiTouchAction multiTouch = new MultiTouchAction(driver);4multiTouch.add(action1).add(action2).perform();5var action = new TouchAction(driver);6action.press({x: x, y: y}).moveTo({x: x1, y: y1}).release().perform();7var multiTouch = new MultiTouchAction(driver);8multiTouch.add(action1).add(action2).perform();9action = TouchAction(driver)10action.press(x=x, y=y).move_to(x=x1, y=y1).release().perform()11multi_touch = MultiTouchAction(driver)12multi_touch.add(action1).add(action2).perform()13action = Appium::TouchAction.new(driver)14action.press(x: x, y: y).move_to(x: x1, y: y1).release().perform()15multi_touch = Appium::MultiTouchAction.new(driver)16multi_touch.add(action1).add(action2).perform()17$action = new Appium\TouchAction($driver);18$action->press(array('x' => $x, 'y' => $y))->moveTo(array('x' => $x1, 'y' => $y1))->release()->perform();19$multiTouch = new Appium\MultiTouchAction($driver);20$multiTouch->add($action1)->add($action2)->perform();21action = new TouchAction(driver)22action.press(x: x, y: y).moveTo(x: x1, y: y1).release().perform()TouchAction
Using AI Code Generation
1TouchAction action = new TouchAction(driver);2action.tap(100, 200).perform();3var action = new TouchAction(driver);4action.tap({x: 100, y: 200}).perform();5swipe(startX, startY, endX, endY, duration)6TouchAction action = new TouchAction(driver);7action.swipe(100, 200, 300, 400, 2000).perform();8var action = new TouchAction(driver);9action.swipe({startX: 100, startY: 200, endX: 300, endY: 400, duration: 2000}).perform();10longPress(xTouchAction
Using AI Code Generation
1TouchAction touchAction = new TouchAction(driver);2touchAction.tap(100, 200).perform();3AppiumDriver appiumDriver = (AppiumDriver) driver;4appiumDriver.tap(1, 100, 200, 1000);5TouchAction touchAction = new TouchAction(driver);6touchAction.tap(100, 200, 1000).perform();7AppiumDriver appiumDriver = (AppiumDriver) driver;8appiumDriver.tap(1, 100, 200, 1000);9TouchAction touchAction = new TouchAction(driver);10touchAction.tap(100, 200, 1000).perform();11AppiumDriver appiumDriver = (AppiumDriver) driver;12appiumDriver.tap(1, 100, 200, 1000);13TouchAction touchAction = new TouchAction(driver);14touchAction.tap(100, 200, 1000).perform();15AppiumDriver appiumDriver = (AppiumDriver) driver;16appiumDriver.tap(1, 100, 200, 1000);17TouchAction touchAction = new TouchAction(driver);18touchAction.tap(100, 200, 1000).perform();19AppiumDriver appiumDriver = (AppiumDriver) driver;20appiumDriver.tap(1, 100, 200, 1000);21TouchAction touchAction = new TouchAction(driver);22touchAction.tap(100, 200, 1000).perform();TouchAction
Using AI Code Generation
1package com.appium.tests;2import java.net.MalformedURLException;3import java.net.URL;4import org.openqa.selenium.By;5import org.openqa.selenium.WebElement;6import org.openqa.selenium.remote.DesiredCapabilities;7import org.testng.annotations.AfterTest;8import org.testng.annotations.BeforeTest;9import org.testng.annotations.Test;10import io.appium.java_client.AppiumDriver;11import io.appium.java_client.TouchAction;12import io.appium.java_client.android.AndroidDriver;13import io.appium.java_client.touch.offset.PointOption;14public class appium {15	AppiumDriver driver;16public void beforeTest() throws MalformedURLException {17DesiredCapabilities caps = new DesiredCapabilities();18caps.setCapability("deviceName", "emulator-5554");19caps.setCapability("platformName", "Android");20caps.setCapability("platformVersion", "7.0");21caps.setCapability("appPackage", "com.android.calculator2");22caps.setCapability("appActivity", "com.android.calculator2.Calculator");23caps.setCapability("noReset", true);TouchAction
Using AI Code Generation
1import java.net.URL;2import org.openqa.selenium.By;3import org.openqa.selenium.remote.DesiredCapabilities;4import io.appium.java_client.android.AndroidDriver;5import io.appium.java_client.android.AndroidElement;6import io.appium.java_client.touch.LongPressOptions;7import io.appium.java_client.touch.offset.ElementOption;8public class touchAction {9	public static void main(String[] args) throws Exception {10		AndroidDriver<AndroidElement> driver;11		DesiredCapabilities caps = new DesiredCapabilities();12		caps.setCapability("deviceName", "Nexus_6_API_25");13		caps.setCapability("platformName", "Android");14		caps.setCapability("platformVersion", "7.1.1");15		caps.setCapability("appPackage", "com.android.chrome");16		caps.setCapability("appActivity", "com.google.android.apps.chrome.Main");17		caps.setCapability("noReset", true);TouchAction
Using AI Code Generation
1TouchAction act = new TouchAction(driver);2act.press(100, 100).perform();3act.moveTo(200, 200).perform();4act.release().perform();5MultiTouchAction multiTouch = new MultiTouchAction(driver);6multiTouch.add(act).perform();7#code to use TouchAction class of appium.webdriver.common.touch_action import TouchAction8act = TouchAction(driver)9act.press(x=100, y=100).perform()10act.move_to(x=200, y=200).perform()11act.release().perform()12#code to use MultiTouchAction class of appium.webdriver.common.touch_action import MultiTouchAction13multiTouch = MultiTouchAction(driver)14multiTouch.add(act).perform()15#code to use TouchAction class of appium_lib import Appium::TouchAction16act.press(x: 100, y: 100).perform17act.move_to(x: 200, y: 200).perform18#code to use MultiTouchAction class of appium_lib import Appium::MultiTouch19multiTouch.add(act).perform20var touchAction = new TouchAction(driver);21touchAction.press({x: 100, y: 100}).perform();22touchAction.moveTo({x: 200, y: 200}).perform();23touchAction.release().perform();24var multiTouchAction = new MultiTouchAction(driver);25multiTouchAction.add(touchAction).perform();26TouchAction act = new TouchAction(driver);27act.Press(100, 100).Perform();28act.MoveTo(200, 200).Perform();29act.Release().Perform();30MultiTouchAction multiTouch = new MultiTouchAction(driver);31multiTouch.Add(act).Perform();TouchAction
Using AI Code Generation
1TouchAction action = new TouchAction(driver);2action.press(100, 200).moveTo(100, 100).release().perform();3var action = new TouchAction(driver);4action.press({x: 100, y: 200}).moveTo({x: 100, y: 100}).release().perform();5TouchAction action = new TouchAction(driver);6action.press(100, 200).moveTo(100, 100).release().perform();7var action = new TouchAction(driver);8action.press({x: 100, y: 200}).moveTo({x: 100, y: 100}).release().perform();Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
