In Android we have a list of key codes which perform set of actions such as press back, return to home screen,lift the call and end call etc.
Below are some of the list of KeyEvent values for respective actions.
3 : "KEYCODE_HOME" 4 : "KEYCODE_BACK" 5 : "KEYCODE_CALL" 6 : "KEYCODE_ENDCALL"
To handle the keys in automation Appium provided a method called press_keycode(). It takes integer value and doesn’t return anything.
Syntax :
driver.press_keycode(integer_value)
Example : In the below example we are launching the app on an Android device and clicking on the button using the ID locator. Then press keycode “4” to go back to the previous screen.
AndroidKeyEvents.py
from appium import webdriver import time from appium.webdriver.common.appiumby import AppiumBy # Step 1 : Create "Desired Capabilities" desired_caps = {} desired_caps['platformName'] = 'Android' desired_caps['automationName'] = 'UiAutomator1' desired_caps['platformVersion'] = '10' desired_caps['deviceName'] = 'Pixel3XL' desired_caps['app'] = ('/Skill2Lead/Appium_Demo_App/Android/Android_Appium_Demo.apk') desired_caps['appPackage'] = 'com.skill2lead.appiumdemo' desired_caps['appActivity'] = 'com.skill2lead.appiumdemo.MainActivity' # Step 2 : Create "Driver object" driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps) # Step 3 : "Click on the button using ID locator value" ele_id = driver.find_element(AppiumBy.ID,"com.skill2lead.appiumdemo:id/EnterValue") ele_id.click() # Step 4 : Keyevent "4" is used to press back key driver.press_keycode(4) time.sleep(2) driver.quit()