APM

Appium with Java Master Cheat Sheet

SETUP · TOOLS & DRIVERS · NATIVE/HYBRID/DESKTOP · FULL DRIVER & SERVER API — END TO END

🎓 Next Gen QA IT Coaching Classes
📞 Mr. Khan Sir  |  8700350994
Appium Java Client Android + iOS Windows (WinAppDriver) Mac (Mac2Driver) TestNG + Maven
1. Setup Overview & Flow · 2. Java & JDK Setup · 3. Node.js & Appium Server · 4. Android Studio & Android SDK
1. Full Setup Flow (Order Matters)
Install order for a working Appium+Java rig
1. JDK → JAVA_HOME 2. Node.js → npm install -g appium 3. Android Studio → Android SDK → ANDROID_HOME 4. appium driver install uiautomator2 5. Xcode (Mac only) → appium driver install xcuitest 6. Appium Inspector (standalone app) 7. IDE (VS Code / IntelliJ) + Maven project 8. Java client dependency in pom.xml
2. Java & JDK Setup
Install JDK 11+ & verify
java -version javac -version
Set JAVA_HOME (macOS/Linux ~/.zshrc)
export JAVA_HOME=$(/usr/libexec/java_home -v 11) export PATH=$JAVA_HOME/bin:$PATH
Windows (System Env Variables)
JAVA_HOME = C:\Program Files\Java\jdk-11 PATH += %JAVA_HOME%\bin
3. Node.js & Appium Server
Install Node (LTS) then Appium
node -v && npm -v npm install -g appium appium -v
Start server / check installed drivers
appium --address 127.0.0.1 --port 4723 appium driver list --installed
appium-doctor – verify full setup health
npm install -g appium-doctor appium-doctor --android appium-doctor --ios
4. Android Studio & SDK
Install via Android Studio → SDK Manager
// SDK Manager → install: // - Android SDK Platform (API 34/33) // - Android SDK Build-Tools // - Android SDK Platform-Tools (adb) // - Android Emulator
Create AVD (emulator) via Device Manager
// Tools → Device Manager → Create Device // pick Pixel 6, API 34 system image
5. Env Variables (ANDROID_HOME) · 6. Appium Drivers · 7. Appium Inspector · 8. Appium Desktop (Legacy GUI)
5. ANDROID_HOME & PATH Setup
macOS/Linux (~/.zshrc or ~/.bash_profile)
export ANDROID_HOME=$HOME/Library/Android/sdk export PATH=$PATH:$ANDROID_HOME/platform-tools export PATH=$PATH:$ANDROID_HOME/emulator export PATH=$PATH:$ANDROID_HOME/tools
Windows (Env Variables)
ANDROID_HOME = C:\Users\you\AppData\Local\Android\Sdk PATH += %ANDROID_HOME%\platform-tools
Verify
adb version emulator -list-avds
6. Appium Drivers (per platform)
PlatformDriver / Install
Android (native/hybrid)uiautomator2
iOS (native/hybrid)xcuitest
Windows Desktopwindows (WinAppDriver-based)
macOS Desktopmac2
Flutter appsflutter (community)
Install / list drivers
appium driver install uiautomator2 appium driver install xcuitest appium driver install mac2 appium driver list --installed
7. Appium Inspector
Standalone GUI app (separate download)
// download from: github.com/appium/appium-inspector/releases // Remote Host: 127.0.0.1 Port: 4723 Path: / // paste JSON capabilities → Start Session // inspect element tree, copy ID/XPath/Accessibility ID // record actions → export as Java code snippet
8. Appium Desktop (Legacy, Deprecated)
Old all-in-one app (server + inspector)
// Appium Desktop = Appium Server GUI + old Inspector // now split into: Appium Server (CLI/npm) + Appium Inspector (separate app) // prefer CLI server + standalone Inspector for new projects
9. VS Code Setup · 10. IntelliJ/Eclipse + Maven · 11. Xcode & iOS Setup · 12. Real Device Setup (Android + iOS)
9. VS Code Setup
Extensions needed for Java + Appium
// Extension Pack for Java (Microsoft) // Maven for Java // Test Runner for Java // (optional) XML Tools for pom.xml editing
Run a TestNG test from VS Code
// Testing icon (flask) in sidebar → Run Test // or terminal: mvn test
10. IntelliJ / Eclipse + Maven Project
Create Maven project structure
src/main/java src/test/java ├─ pages/ // Page Object classes ├─ tests/ // TestNG test classes └─ utils/ // DriverFactory, helpers pom.xml testng.xml
Run via Maven from IntelliJ terminal
mvn clean test -Dsurefire.suiteXmlFiles=testng.xml
11. Xcode & iOS Setup (Mac only)
Install Xcode + command line tools
xcode-select --install sudo xcode-select -s /Applications/Xcode.app xcrun simctl list devices
WebDriverAgent (auto-built by xcuitest driver)
// first run builds WDA via xcodebuild — can take minutes // needs a free/paid Apple Developer signing team for real device
12. Real Device Setup
Android real device
// enable Developer Options → USB Debugging adb devices // should list device serial
iOS real device
// trust computer on device, set signing team in WDA // capability: xcodeOrgId, xcodeSigningId, udid
13. Desired Capabilities – Native Android · 14. Native iOS · 15. Hybrid App (WebView) · 16. Desktop App (Windows – WinAppDriver)
13. Native Android Capabilities (Java)
UiAutomator2Options
UiAutomator2Options options = new UiAutomator2Options(); options.setPlatformName("Android"); options.setAutomationName("UiAutomator2"); options.setDeviceName("Pixel_6_API_34"); options.setApp("/path/app.apk"); options.setAppPackage("com.example.app"); options.setAppActivity(".MainActivity"); options.setNoReset(true); AndroidDriver driver = new AndroidDriver( new URL("http://127.0.0.1:4723"), options);
14. Native iOS Capabilities (Java)
XCUITestOptions
XCUITestOptions options = new XCUITestOptions(); options.setPlatformName("iOS"); options.setAutomationName("XCUITest"); options.setDeviceName("iPhone 15"); options.setPlatformVersion("17.0"); options.setApp("/path/app.app"); options.setBundleId("com.example.app"); IOSDriver driver = new IOSDriver( new URL("http://127.0.0.1:4723"), options);
15. Hybrid App (WebView) Setup
Capability to allow webview inspection
options.setCapability("autoWebview", false); options.setCapability("chromedriverAutodownload", true);
List & switch contexts
Set<String> contexts = driver.getContextHandles(); // e.g. [NATIVE_APP, WEBVIEW_com.example.app] driver.context("WEBVIEW_com.example.app"); driver.findElement(By.cssSelector("#login-btn")).click(); driver.context("NATIVE_APP");
16. Desktop App – Windows (WinAppDriver)
Setup: enable Dev Mode + start WinAppDriver
// Settings → Update & Security → For Developers → Developer Mode ON // install WinAppDriver.msi, run WinAppDriver.exe (port 4723)
Capabilities (Java) – Windows driver
WindowsOptions options = new WindowsOptions(); options.setApp("C:\\Path\\App.exe"); options.setPlatformName("Windows"); WindowsDriver driver = new WindowsDriver( new URL("http://127.0.0.1:4723"), options);
17. Desktop App – macOS (Mac2Driver) · 18. Locator Strategies · 19. Waits & Synchronization · 20. Gestures (W3C Actions)
17. Desktop App – macOS (Mac2Driver)
Enable accessibility permission first
// System Settings → Privacy & Security → Accessibility // allow Terminal / Appium to control the Mac appium driver install mac2
Capabilities (Java) – Mac2 driver
Mac2Options options = new Mac2Options(); options.setBundleId("com.apple.calculator"); Mac2Driver driver = new Mac2Driver( new URL("http://127.0.0.1:4723"), options);
18. Locator Strategies
StrategyExample
IDBy.id("com.app:id/btn")
Accessibility IDAppiumBy.accessibilityId("login")
XPath//android.widget.Button[@text='Login']
UiAutomator (Android)androidUIAutomator("new UiSelector()...")
NSPredicate (iOS)iOSNsPredicateString("name=='Login'")
Class Chain (iOS)iOSClassChain("**/XCUIElementTypeButton")
19. Waits & Synchronization
Explicit wait (recommended)
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15)); WebElement el = wait.until(ExpectedConditions.elementToBeClickable( AppiumBy.accessibilityId("login")));
Fluent wait w/ polling
Wait<AndroidDriver> fw = new FluentWait<>(driver) .withTimeout(Duration.ofSeconds(20)) .pollingEvery(Duration.ofMillis(500)) .ignoring(NoSuchElementException.class);
20. Gestures (W3C Actions)
Swipe via mobile: command (simplest)
Map<String, Object> params = new HashMap<>(); params.put("direction", "up"); params.put("percent", 0.75); driver.executeScript("mobile: swipeGesture", params);
Long press
Map<String, Object> lp = new HashMap<>(); lp.put("elementId", ((RemoteWebElement) el).getId()); lp.put("duration", 1500); driver.executeScript("mobile: longClickGesture", lp);
21. Platform-Specific Commands · 22. Context Switching Detail · 23. Page Object Model (Java) · 24. TestNG + Maven Project Setup
21. Platform-Specific Commands
ActionAndroidiOS
Hide keyboarddriver.hideKeyboard()same
Backdriver.navigate().back()N/A
Launch/TerminateactivateApp()/terminateApp()same
Install appinstallApp(path)installApp(path)
22. Context Switching (Hybrid Detail)
Wait for webview context to appear
new WebDriverWait(driver, Duration.ofSeconds(10)).until( d -> ((AndroidDriver) d).getContextHandles().size() > 1); for (String ctx : driver.getContextHandles()) { if (ctx.contains("WEBVIEW")) driver.context(ctx); }
23. Page Object Model (Java)
POM with PageFactory + AppiumFieldDecorator
public class LoginPage { AndroidDriver driver; @AndroidFindBy(accessibility = "username") WebElement username; @AndroidFindBy(accessibility = "loginBtn") WebElement loginBtn; public LoginPage(AndroidDriver driver) { this.driver = driver; PageFactory.initElements( new AppiumFieldDecorator(driver), this); } public void login(String user) { username.sendKeys(user); loginBtn.click(); } }
24. TestNG + Maven Project Setup
pom.xml core dependencies
<dependency> <groupId>io.appium</groupId> <artifactId>java-client</artifactId> <version>9.3.0</version> </dependency>
Base test class
@BeforeMethod public void setUp() throws Exception { driver = new AndroidDriver( new URL("http://127.0.0.1:4723"), options); } @AfterMethod public void tearDown() { if(driver != null) driver.quit(); }
25. Handy ADB Commands · 26. Common Exceptions & Fixes · 27. Cloud Execution (BrowserStack/Sauce Labs) · 28. Best Practices
25. Handy ADB Commands
PurposeCommand
List devicesadb devices
Install APKadb install app.apk
Clear app dataadb shell pm clear pkg
Screenshotadb shell screencap /sdcard/s.png
Logsadb logcat
Get current activityadb shell dumpsys window | grep mCurrentFocus
26. Common Exceptions & Fixes
ExceptionFix
NoSuchElementExceptionVerify via Inspector; add explicit wait
StaleElementReferenceExceptionRe-locate element before use
SessionNotCreatedExceptionCheck driver install & capability values
Connection refusedAppium server not running on that port
27. Cloud Execution
BrowserStack capability example (Java)
options.setCapability("bstack:options", Map.of( "deviceName", "Samsung Galaxy S23", "osVersion", "13.0", "projectName", "MyApp Tests")); driver = new AndroidDriver(new URL( "https://user:key@hub-cloud.browserstack.com/wd/hub"), options);
28. Best Practices
Checklist
✔ Accessibility ID/ID over XPath for speed ✔ Page Object Model + PageFactory always ✔ Explicit waits only, never mix w/ implicit ✔ noReset/fullReset controlled per test ✔ Parallel run via TestNG + multiple devices ✔ Screenshot + logs captured on failure ✔ Pin java-client + driver versions together
29. App Lifecycle Methods · 30. Device State Methods · 31. Files, Clipboard & Storage · 32. WebElement Core Methods
29. App Lifecycle Methods
MethodPurpose
isAppInstalled(bundleId)check install state
installApp(path)install app
removeApp(bundleId)uninstall app
activateApp(bundleId)bring app to foreground
terminateApp(bundleId)kill app process
queryAppState(bundleId)0-4 running state enum
runAppInBackground(dur)send to bg, return after N sec
30. Device State Methods
MethodPurpose
lockDevice() / unlockDevice()lock/unlock screen
isDeviceLocked()check lock state
getDeviceTime()device's current time
rotate(ScreenOrientation)set LANDSCAPE/PORTRAIT
getOrientation()read current orientation
getSystemTime()epoch time from server
31. Files, Clipboard & Storage
MethodPurpose
pushFile(path, bytes)copy file to device
pullFile(path)copy file from device (base64)
pullFolder(path)zip & pull a folder
getClipboardText()read device clipboard
setClipboard(text)write device clipboard
32. WebElement Core Methods
MethodPurpose
click()tap element
sendKeys(text)type text
clear()clear text field
getText()visible text
getAttribute(name)read any attribute
getTagName()element class/type
33. WebElement State/Geometry · 34. Android-Only Driver Methods · 35. Android Emulator Console Methods · 36. iOS-Only Driver Methods
33. WebElement State & Geometry
MethodPurpose
isDisplayed()visible on screen?
isEnabled()interactable?
isSelected()checkbox/radio/toggle state
getLocation()x/y position (Point)
getSize()width/height (Dimension)
getRect()location + size (Rectangle)
34. Android-Only Driver Methods
MethodPurpose
getCurrentActivity()foreground activity name
getCurrentPackage()foreground package name
startActivity(intent)launch specific activity
toggleWifi()toggle WiFi radio
toggleAirplaneMode()toggle airplane mode
toggleLocationServices()toggle GPS
openNotifications()pull down notification shade
35. Android Emulator-Only Methods
MethodPurpose
getSystemBars()status/nav bar dimensions
getDisplayDensity()screen DPI
getPerformanceData()CPU/memory/battery/network
getSupportedPerformanceMetrics()list available metrics
sendSMS(phone, msg)emulator-only, fake SMS
gsmCall() / gsmSignal()emulator-only, simulate call/signal
36. iOS-Only Driver Methods
MethodPurpose
shake()simulate device shake
performTouchID(match)simulate Touch ID pass/fail
toggleTouchIDEnrollment()enroll/unenroll simulator Touch ID
getSettings() / updateSettings()read/update session settings
hideKeyboard(strategy)tap outside / press Done key
37. mobile: Command Catalog – Android · 38. mobile: Command Catalog – iOS · 39. TouchAction & MultiTouchAction (Legacy) · 40. Appium Settings API
37. mobile: Commands – Android (executeScript)
CommandPurpose
mobile: swipeGesturedirectional swipe
mobile: scrollGesturescroll a container
mobile: longClickGesturelong press
mobile: dragGesturedrag element to point
mobile: pinchOpenGesture / pinchCloseGesturezoom in/out
mobile: shellrun raw adb shell command
mobile: startScreenStreaminglive device screen stream
38. mobile: Commands – iOS (executeScript)
CommandPurpose
mobile: swipedirectional swipe
mobile: scrollscroll to element/direction
mobile: taptap at coordinates
mobile: dragFromToForDurationdrag gesture w/ timing
mobile: alertaccept/dismiss/getButtons on alert
mobile: pressButtonhome/volume/lock hardware button
39. TouchAction & MultiTouchAction (Legacy)
Deprecated in favor of W3C Actions, but still asked in interviews & seen in older frameworks.
Single-finger TouchAction chain
new TouchAction<>(driver) .press(PointOption.point(100,500)) .waitAction(WaitOptions.waitOptions(Duration.ofMillis(500))) .moveTo(PointOption.point(100,100)) .release().perform();
MultiTouchAction – multiple fingers
new MultiTouchAction(driver) .add(touchAction1).add(touchAction2).perform();
40. Appium Settings API
Runtime settings via setSetting()
driver.setSetting("ignoreUnimportantViews", true); driver.setSetting("waitForIdleTimeout", 0); driver.setSetting("snapshotMaxDepth", 60); Map<String,Object> all = driver.getSettings();
41. Appium Server CLI Flags · 42. Server Security & Relaxed Security · 43. Session Management & Capabilities · 44. Appium Extensions CLI (Drivers/Plugins)
41. Appium Server CLI Flags
FlagPurpose
--address / --portbind host:port
--base-pathcustom URL path prefix
--log-leveldebug/info/warn/error
--log <file>write server logs to file
--session-overrideallow only 1 active session
--allow-corsenable CORS for browser clients
42. Server Security & Relaxed Security
FlagPurpose
--relaxed-securityunlock all insecure features
--allow-insecure <list>whitelist specific features
--deny-insecure <list>blacklist specific features
e.g. adb_shellneeded for mobile: shell command
43. Session Management & Capabilities
REST endpoints Appium server exposes
POST /session // create new session DELETE /session/:id // quit session GET /sessions // list active sessions POST /session/:id/execute // run "mobile:" script
Java side session end
driver.quit(); // always call in @AfterMethod
44. Appium Extensions CLI (Drivers/Plugins)
CommandPurpose
appium driver listshow available/installed drivers
appium driver update <name>update a driver
appium plugin install <name>e.g. images, execute-driver
appium plugin list --installedlist installed plugins
appium --use-plugins=<names>enable plugins at server start