There are situations, where we have to long press on key buttons of screen to trigger an event, to hold the element or type a letter,
LongPress can be done on a co-ordinate or on an element, we will see how to achieve this.
In Appium, we have one method LongPress() which is under class TouckAction
Refer the API doc link [java-client version >= 6.1.0 as of now]
public T longPress(LongPressOptions longPressOptions)
public T longPress(PointOption longPressOptions)
We will see how to long press on an element, let’s try with the dialer android app, on the keypad screen, if you long press on the Zero number, + will be displayed, that we will automate in this post –
package com.test.apiTest; import java.net.MalformedURLException; import java.net.URL; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.DesiredCapabilities; import org.testng.Assert; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileElement; import io.appium.java_client.TouchAction; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.touch.LongPressOptions; import io.appium.java_client.touch.offset.ElementOption; public class LongPress { static DesiredCapabilities cap; static AppiumDriver<MobileElement> driver; @BeforeTest static void setup() throws MalformedURLException{ cap = new DesiredCapabilities(); cap.setCapability("platformName", "Android"); cap.setCapability("deviceName", "pixelxlo26"); cap.setCapability("appPackage", "com.google.android.dialer"); cap.setCapability("appActivity", ".DialtactsActivity"); driver = new AndroidDriver<MobileElement>(new URL("http://127.0.0.1:4723/wd/hub"), cap); } @Test static void TestLongPress() throws InterruptedException{ Thread.sleep(2000); WebElement Add = driver.findElement(By.id("fab")); Add.click(); Thread.sleep(500); WebElement Zero = driver.findElement(By.xpath("//android.widget.TextView[@text='0']")); new TouchAction(driver) .longPress(LongPressOptions.longPressOptions().withElement((ElementOption.element(Zero)))) .release().perform(); //verify if the + sign displayed Assert.assertEquals(driver.findElement(By.id("digits")).getText(), "+"); } }
for e.g: On dialer app, to dial “+”, we need to long press zero (“0”) to print +

Try to long press on “zero” button to print +