0
# Application Management
1
2
Application lifecycle management including installation, background/foreground control, and state querying across mobile platforms. These capabilities enable comprehensive app testing workflows and device state management.
3
4
## Capabilities
5
6
### App State Management
7
8
Control application foreground/background state and query current application status across mobile platforms.
9
10
```python {.api}
11
def background_app(self, seconds: int):
12
"""
13
Put the current application in background for specified time.
14
15
Args:
16
seconds (int): Duration to keep app in background (seconds)
17
Use -1 to keep in background indefinitely
18
"""
19
20
def activate_app(self, app_id: str):
21
"""
22
Bring application to foreground by app ID.
23
24
Args:
25
app_id (str): Application identifier (bundle ID for iOS, package name for Android)
26
"""
27
28
def terminate_app(self, app_id: str, **options):
29
"""
30
Terminate running application.
31
32
Args:
33
app_id (str): Application identifier
34
**options: Platform-specific termination options
35
timeout (int): Termination timeout in milliseconds
36
"""
37
38
def query_app_state(self, app_id: str) -> int:
39
"""
40
Query the current state of an application.
41
42
Args:
43
app_id (str): Application identifier
44
45
Returns:
46
int: Application state constant:
47
0 - NOT_INSTALLED
48
1 - NOT_RUNNING
49
2 - RUNNING_IN_BACKGROUND_SUSPENDED
50
3 - RUNNING_IN_BACKGROUND
51
4 - RUNNING_IN_FOREGROUND
52
"""
53
```
54
55
### App Installation Management
56
57
Install, uninstall, and verify application presence on mobile devices.
58
59
```python {.api}
60
def is_app_installed(self, bundle_id: str) -> bool:
61
"""
62
Check if application is installed on device.
63
64
Args:
65
bundle_id (str): Application bundle ID (iOS) or package name (Android)
66
67
Returns:
68
bool: True if app is installed, False otherwise
69
"""
70
71
def install_app(self, app_path: str, **options):
72
"""
73
Install application on device.
74
75
Args:
76
app_path (str): Path to application file (.apk for Android, .app/.ipa for iOS)
77
**options: Platform-specific installation options
78
replace (bool): Replace existing app if installed
79
timeout (int): Installation timeout in milliseconds
80
allowTestPackages (bool): Allow test packages (Android)
81
useSdcard (bool): Install on SD card (Android)
82
grantPermissions (bool): Grant runtime permissions (Android)
83
"""
84
85
def remove_app(self, app_id: str, **options):
86
"""
87
Uninstall application from device.
88
89
Args:
90
app_id (str): Application identifier
91
**options: Platform-specific removal options
92
keepData (bool): Keep application data after removal
93
timeout (int): Removal timeout in milliseconds
94
"""
95
```
96
97
### App Content Access
98
99
Access application strings and localized content for testing and validation.
100
101
```python {.api}
102
def app_strings(self, language: str = None, string_file: str = None) -> dict:
103
"""
104
Get application strings/localized content.
105
106
Args:
107
language (str, optional): Language code (e.g., 'en', 'es', 'fr')
108
string_file (str, optional): Specific string file to read
109
110
Returns:
111
dict: Dictionary of string keys and localized values
112
"""
113
```
114
115
## Usage Examples
116
117
### Basic App Lifecycle Management
118
119
```python
120
from appium import webdriver
121
from appium.options.android import UiAutomator2Options
122
from appium.webdriver.common.applicationstate import ApplicationState
123
124
# Setup driver
125
options = UiAutomator2Options()
126
options.platform_name = "Android"
127
options.device_name = "Android Emulator"
128
driver = webdriver.Remote("http://localhost:4723", options=options)
129
130
# Check if app is installed
131
app_id = "com.example.myapp"
132
if driver.is_app_installed(app_id):
133
print("App is already installed")
134
else:
135
# Install the app
136
driver.install_app("/path/to/myapp.apk", replace=True)
137
138
# Query app state
139
state = driver.query_app_state(app_id)
140
if state == ApplicationState.NOT_RUNNING:
141
driver.activate_app(app_id)
142
143
# Put app in background for 5 seconds
144
driver.background_app(5)
145
146
# Check state after backgrounding
147
state = driver.query_app_state(app_id)
148
print(f"App state: {state}")
149
```
150
151
### Advanced Installation Options
152
153
```python
154
# Android installation with specific options
155
driver.install_app(
156
"/path/to/app.apk",
157
replace=True,
158
grantPermissions=True,
159
allowTestPackages=True,
160
timeout=60000
161
)
162
163
# iOS installation
164
driver.install_app("/path/to/app.ipa", replace=False)
165
166
# Verify installation success
167
if driver.is_app_installed("com.example.app"):
168
print("Installation successful")
169
```
170
171
### App State Monitoring
172
173
```python
174
import time
175
from appium.webdriver.common.applicationstate import ApplicationState
176
177
def monitor_app_state(driver, app_id, duration=30):
178
"""Monitor app state changes over time."""
179
start_time = time.time()
180
181
while time.time() - start_time < duration:
182
state = driver.query_app_state(app_id)
183
184
if state == ApplicationState.NOT_INSTALLED:
185
print("App not installed")
186
elif state == ApplicationState.NOT_RUNNING:
187
print("App not running")
188
elif state == ApplicationState.RUNNING_IN_BACKGROUND:
189
print("App in background")
190
elif state == ApplicationState.RUNNING_IN_FOREGROUND:
191
print("App in foreground")
192
193
time.sleep(2)
194
195
# Usage
196
monitor_app_state(driver, "com.example.myapp", 60)
197
```
198
199
### App Content and Localization
200
201
```python
202
# Get all app strings in default language
203
strings = driver.app_strings()
204
print(f"Found {len(strings)} strings")
205
206
# Get strings for specific language
207
spanish_strings = driver.app_strings("es")
208
print(f"Spanish strings: {spanish_strings}")
209
210
# Get strings from specific file
211
specific_strings = driver.app_strings(string_file="strings.xml")
212
213
# Use strings for validation
214
expected_title = strings.get("app_title", "Default Title")
215
actual_title = driver.find_element("id", "title").text
216
assert actual_title == expected_title
217
```
218
219
### Multi-App Testing Workflow
220
221
```python
222
def multi_app_test_workflow(driver):
223
"""Example workflow testing multiple apps."""
224
apps = [
225
{"id": "com.example.app1", "path": "/path/to/app1.apk"},
226
{"id": "com.example.app2", "path": "/path/to/app2.apk"}
227
]
228
229
# Install all test apps
230
for app in apps:
231
if not driver.is_app_installed(app["id"]):
232
print(f"Installing {app['id']}")
233
driver.install_app(app["path"])
234
235
# Test app switching
236
for app in apps:
237
print(f"Testing {app['id']}")
238
239
# Activate app
240
driver.activate_app(app["id"])
241
242
# Verify app is in foreground
243
state = driver.query_app_state(app["id"])
244
assert state == ApplicationState.RUNNING_IN_FOREGROUND
245
246
# Perform app-specific tests
247
perform_app_tests(driver, app["id"])
248
249
# Background the app
250
driver.background_app(2)
251
252
# Cleanup - remove test apps
253
for app in apps:
254
if driver.is_app_installed(app["id"]):
255
driver.remove_app(app["id"])
256
257
def perform_app_tests(driver, app_id):
258
"""Placeholder for app-specific test logic."""
259
pass
260
```
261
262
### Error Handling
263
264
```python
265
from selenium.common.exceptions import WebDriverException
266
267
try:
268
# Attempt to install app
269
driver.install_app("/path/to/app.apk", timeout=30000)
270
except WebDriverException as e:
271
print(f"Installation failed: {e}")
272
273
# Try alternative approach
274
if "INSTALL_FAILED_UPDATE_INCOMPATIBLE" in str(e):
275
print("Removing existing app and retrying...")
276
driver.remove_app("com.example.app")
277
driver.install_app("/path/to/app.apk", replace=True)
278
279
# Safe app state checking
280
def safe_query_app_state(driver, app_id):
281
"""Safely query app state with error handling."""
282
try:
283
return driver.query_app_state(app_id)
284
except WebDriverException:
285
# App might not be installed or driver issue
286
return ApplicationState.NOT_INSTALLED
287
288
state = safe_query_app_state(driver, "com.example.app")
289
```
290
291
## Types
292
293
```python {.api}
294
# Application state constants
295
class ApplicationState:
296
NOT_INSTALLED: int = 0
297
NOT_RUNNING: int = 1
298
RUNNING_IN_BACKGROUND_SUSPENDED: int = 2
299
RUNNING_IN_BACKGROUND: int = 3
300
RUNNING_IN_FOREGROUND: int = 4
301
302
# Type definitions
303
AppId = str # Bundle ID (iOS) or package name (Android)
304
AppPath = str # File path to application binary
305
BackgroundDuration = int # Seconds, -1 for indefinite
306
AppStrings = Dict[str, str] # Localized string key-value pairs
307
InstallationOptions = Dict[str, Union[bool, int, str]]
308
```