0
# Application Management
1
2
Complete application lifecycle management including installation, launching, stopping, monitoring, and permission handling for Android applications.
3
4
## Capabilities
5
6
### Application Installation and Removal
7
8
Install, uninstall, and manage Android applications.
9
10
```python { .api }
11
class Device:
12
def app_install(self, data: str):
13
"""
14
Install Android application.
15
16
Parameters:
17
- data: APK file path, URL, or file object
18
"""
19
20
def app_uninstall(self, package_name: str) -> bool:
21
"""
22
Uninstall application.
23
24
Parameters:
25
- package_name: Package name to uninstall
26
27
Returns:
28
bool: True if uninstall successful
29
"""
30
31
def app_uninstall_all(self, excludes=[], verbose=False) -> List[str]:
32
"""
33
Uninstall all third-party applications.
34
35
Parameters:
36
- excludes: Package names to exclude from uninstall
37
- verbose: Print uninstall progress
38
39
Returns:
40
List of uninstalled package names
41
"""
42
```
43
44
Usage examples:
45
46
```python
47
d = u2.connect()
48
49
# Install APK from file
50
d.app_install("/path/to/app.apk")
51
52
# Install APK from URL
53
d.app_install("https://example.com/app.apk")
54
55
# Uninstall specific app
56
success = d.app_uninstall("com.example.app")
57
if success:
58
print("App uninstalled successfully")
59
60
# Uninstall all third-party apps except specified
61
excluded = ["com.important.app", "com.needed.tool"]
62
uninstalled = d.app_uninstall_all(excludes=excluded, verbose=True)
63
print(f"Uninstalled {len(uninstalled)} apps")
64
```
65
66
### Application Launch and Control
67
68
Start, stop, and control application execution.
69
70
```python { .api }
71
class Device:
72
def app_start(self, package_name: str, activity: Optional[str] = None, wait: bool = False, stop: bool = False, use_monkey: bool = False):
73
"""
74
Launch application.
75
76
Parameters:
77
- package_name: Package name to launch
78
- activity: Specific activity to launch (optional)
79
- wait: Wait for app to fully start
80
- stop: Stop app before starting
81
- use_monkey: Use monkey command for launch
82
"""
83
84
def app_stop(self, package_name: str):
85
"""
86
Stop running application.
87
88
Parameters:
89
- package_name: Package name to stop
90
"""
91
92
def app_stop_all(self, excludes=[]) -> List[str]:
93
"""
94
Stop all third-party applications.
95
96
Parameters:
97
- excludes: Package names to exclude from stopping
98
99
Returns:
100
List of stopped package names
101
"""
102
103
def app_clear(self, package_name: str):
104
"""
105
Clear application data.
106
107
Parameters:
108
- package_name: Package name to clear
109
"""
110
```
111
112
Usage examples:
113
114
```python
115
d = u2.connect()
116
117
# Basic app launch
118
d.app_start("com.android.settings")
119
120
# Launch with specific activity
121
d.app_start("com.example.app", activity=".MainActivity")
122
123
# Stop app before launching (fresh start)
124
d.app_start("com.example.app", stop=True, wait=True)
125
126
# Stop running app
127
d.app_stop("com.example.app")
128
129
# Stop all apps except system and specified
130
excluded = ["com.android.systemui", "com.important.service"]
131
stopped = d.app_stop_all(excludes=excluded)
132
print(f"Stopped {len(stopped)} apps")
133
134
# Clear app data
135
d.app_clear("com.example.app") # Reset app to fresh state
136
```
137
138
### Application Monitoring and Status
139
140
Monitor application state and retrieve information.
141
142
```python { .api }
143
class Device:
144
def app_current(self) -> Dict[str, Any]:
145
"""
146
Get current foreground application info.
147
148
Returns:
149
Dict with package, activity, and pid information
150
151
Raises:
152
DeviceError: If unable to get current app
153
"""
154
155
def app_wait(self, package_name: str, timeout: float = 20.0, front=False) -> int:
156
"""
157
Wait for application to launch.
158
159
Parameters:
160
- package_name: Package name to wait for
161
- timeout: Maximum wait time in seconds
162
- front: Wait for app to be in foreground
163
164
Returns:
165
int: Process ID (PID) of app, 0 if launch failed
166
"""
167
168
def wait_activity(self, activity: str, timeout=10) -> bool:
169
"""
170
Wait for specific activity to appear.
171
172
Parameters:
173
- activity: Activity name to wait for
174
- timeout: Maximum wait time in seconds
175
176
Returns:
177
bool: True if activity appeared
178
"""
179
```
180
181
Usage examples:
182
183
```python
184
d = u2.connect()
185
186
# Get current app info
187
current = d.app_current()
188
print(f"Current app: {current['package']}")
189
print(f"Current activity: {current['activity']}")
190
191
# Launch app and wait for it to start
192
d.app_start("com.example.app")
193
pid = d.app_wait("com.example.app", timeout=30)
194
if pid > 0:
195
print(f"App started with PID: {pid}")
196
197
# Wait for specific activity
198
d.app_start("com.example.app", activity=".LoginActivity")
199
if d.wait_activity(".MainActivity", timeout=15):
200
print("Main activity loaded")
201
```
202
203
### Application Information and Listing
204
205
Retrieve application metadata and list installed/running applications.
206
207
```python { .api }
208
class Device:
209
def app_info(self, package_name: str) -> Dict[str, Any]:
210
"""
211
Get application information.
212
213
Parameters:
214
- package_name: Package name to query
215
216
Returns:
217
Dict with versionName and versionCode
218
219
Raises:
220
AppNotFoundError: If app not found
221
"""
222
223
def app_list(self, filter: str = None) -> List[str]:
224
"""
225
List installed applications.
226
227
Parameters:
228
- filter: pm list packages filter options
229
230
Returns:
231
List of package names
232
"""
233
234
def app_list_running(self) -> List[str]:
235
"""
236
List currently running applications.
237
238
Returns:
239
List of running package names
240
"""
241
```
242
243
Usage examples:
244
245
```python
246
d = u2.connect()
247
248
# Get app version info
249
try:
250
info = d.app_info("com.example.app")
251
print(f"Version: {info['versionName']} ({info['versionCode']})")
252
except u2.AppNotFoundError:
253
print("App not installed")
254
255
# List all installed apps
256
all_apps = d.app_list()
257
print(f"Total apps: {len(all_apps)}")
258
259
# List third-party apps only
260
third_party = d.app_list("-3")
261
print(f"Third-party apps: {len(third_party)}")
262
263
# List running apps
264
running = d.app_list_running()
265
print(f"Running apps: {running}")
266
```
267
268
### Session Management
269
270
Create and manage application sessions with lifecycle monitoring.
271
272
```python { .api }
273
class Device:
274
def session(self, package_name: str, attach: bool = False) -> Session:
275
"""
276
Create monitored application session.
277
278
Parameters:
279
- package_name: Package name to monitor
280
- attach: Attach to existing session instead of launching
281
282
Returns:
283
Session instance for lifecycle management
284
"""
285
286
class Session(Device):
287
def __init__(self, dev: adbutils.AdbDevice, package_name: str):
288
"""Initialize session with device and package name"""
289
290
@property
291
def pid(self) -> int:
292
"""Process ID of monitored application"""
293
294
def running(self) -> bool:
295
"""Check if monitored application is still running"""
296
297
def restart(self):
298
"""Restart monitored application"""
299
300
def close(self):
301
"""Close/stop monitored application"""
302
303
def __enter__(self):
304
"""Context manager entry"""
305
306
def __exit__(self, exc_type, exc_val, exc_tb):
307
"""Context manager exit"""
308
```
309
310
Usage examples:
311
312
```python
313
d = u2.connect()
314
315
# Create session (launches app)
316
session = d.session("com.example.app")
317
print(f"App PID: {session.pid}")
318
319
# Check if app is running
320
if session.running():
321
print("App is running")
322
323
# Use session as context manager
324
with d.session("com.example.app") as session:
325
# App is automatically launched
326
session.click(100, 200)
327
session.send_keys("test input")
328
329
# Restart if needed
330
if not session.running():
331
session.restart()
332
333
# App is automatically stopped when exiting context
334
335
# Attach to existing session
336
existing_session = d.session("com.example.app", attach=True)
337
```
338
339
### Permission Management
340
341
Automatically grant application permissions.
342
343
```python { .api }
344
class Device:
345
def app_auto_grant_permissions(self, package_name: str):
346
"""
347
Automatically grant all permissions for application.
348
349
Parameters:
350
- package_name: Package name to grant permissions
351
352
Note:
353
- Requires Android 6.0+ (API 23+)
354
- App must target SDK 22+
355
- Only grants runtime permissions
356
"""
357
```
358
359
Usage examples:
360
361
```python
362
d = u2.connect()
363
364
# Grant all permissions after installing app
365
d.app_install("/path/to/app.apk")
366
d.app_auto_grant_permissions("com.example.app")
367
368
# Useful for testing apps that require multiple permissions
369
d.app_auto_grant_permissions("com.camera.app") # Camera, storage, etc.
370
d.app_auto_grant_permissions("com.location.app") # Location permissions
371
```