Saturday, September 16, 2017

Mobile Device - Perform Swipe / Scroll

Example : How to perform Swipe screen using Appium for Mobile device.


package com.vikas.automation.example;

import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.AndroidMobileCapabilityType;
import io.appium.java_client.remote.MobileCapabilityType;

public class AndroidLinkedInTest {

 @Test
 public void testMobileSwipe() throws MalformedURLException {

  URL appiumUrl = new URL("http://127.0.0.1:4723/wd/hub");
  DesiredCapabilities caps = new DesiredCapabilities();
  caps.setCapability(MobileCapabilityType.APP,
    "C:\\Users\\vikas\\O2\\apps\\BookMyShow_5.3.0.apk");
  caps.setCapability(MobileCapabilityType.PLATFORM_NAME, "android");
  caps.setCapability(MobileCapabilityType.DEVICE_NAME, "OnePlus3T");
  caps.setCapability(MobileCapabilityType.NO_RESET, true);
  caps.setCapability(MobileCapabilityType.FULL_RESET, false);
  //caps.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, "");
  caps.setCapability(AndroidMobileCapabilityType.APP_WAIT_ACTIVITY, "*");
  AppiumDriver<WebElement> driver = new AndroidDriver<WebElement>(appiumUrl, caps);
  driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

  //swipeUp(driver);
  swipeToRight(driver);
  System.out.println("Swipe completed");
  
  driver.quit();
 }

 private void swipeUp(AppiumDriver<WebElement> driver) {

  System.out.println(driver.manage().window().getSize());
  TouchAction action = new TouchAction(driver);
  // Just for beginning and manking it simple lets hardcode the x and y 
  int startX = 540;
  int startY = 1680;
  int endX = 540;
  int endY = 240;
  // Only need to give start and end point, No need of offset
  action.press(startX, startY).waitAction(Duration.ofMillis(500)).moveTo(endX,endY).release().perform();
  
 }
 private void swipeToRight(AppiumDriver<WebElement> driver) {

  // Take dynamic X and Y coordinates , below code should support devices with diffrent screen sizes
  Dimension d =driver.manage().window().getSize();
  int y = d.height/2;
  int endX = d.width/4;
  int startX = endX * 3;
  TouchAction action = new TouchAction(driver);  
  action.press(startX, y).waitAction(Duration.ofMillis(500)).moveTo(endX,y).release().perform();
 }
}

No comments:

Post a Comment