Simulating back, home button in Android in Appium

We can use below lines of code to simulate the back and home button of Android phone in Appium.

To simulate the Home button, we can use below line of code.

driver.pressKeyCode(AndroidKeyCode.HOME);

To simulate the back button, we can use below lines of code.

//driver.navigate().back();
driver.pressKeyCode(AndroidKeyCode.BACK);

Here is the complete example on Whatsapp.

package nativeapptests;

import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidKeyCode;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.net.URL;
import java.util.concurrent.TimeUnit;

public class SimulateButtonsAndroidPhone
{
    private AndroidDriver driver;

    @Test
    public void test() throws Exception{

        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("platformName", "Android");
        capabilities.setCapability("platformVersion", "4.4.4");
        capabilities.setCapability("deviceName", "sagarcell");
        capabilities.setCapability("browser_Name", "Android");
        capabilities.setCapability("appPackage", "com.whatsapp");
        capabilities.setCapability("appActivity","com.whatsapp.Main");

        try {
            driver = new AndroidDriver(new URL("https://127.0.0.1:4723/wd/hub"), capabilities) {
            };

           driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
           new WebDriverWait(driver,20).
                   until(ExpectedConditions.elementToBeClickable(By.className("android.widget.TextView")));
           WebElement contactsTextViewElement =
                   driver.findElement(By.className("android.widget.TextView"));
            driver.performTouchAction(new TouchAction(driver).tap(contactsTextViewElement));
            //driver.navigate().back();
            driver.pressKeyCode(AndroidKeyCode.BACK);
            driver.pressKeyCode(AndroidKeyCode.HOME);
            Thread.sleep(5000);

        }catch(Exception ex) {
            System.out.println(ex.toString());
        }finally {
            //quit the browser
            driver.quit();
        }
    }
}

You may also like...