0
# Device Connection and Management
1
2
Core functionality for connecting to Android devices and managing device state, including device discovery, connection establishment, and device information retrieval.
3
4
## Capabilities
5
6
### Device Connection
7
8
Connect to Android devices via ADB using serial numbers or automatic device detection.
9
10
```python { .api }
11
def connect(serial: Union[str, adbutils.AdbDevice] = None) -> Device:
12
"""
13
Connect to Android device.
14
15
Parameters:
16
- serial: Device serial number or AdbDevice instance. If None, uses ANDROID_SERIAL environment variable or auto-detects device.
17
18
Returns:
19
Device instance for automation
20
21
Raises:
22
ConnectError: If device connection fails
23
"""
24
25
def connect_usb(serial: Optional[str] = None) -> Device:
26
"""
27
Connect to Android device via USB/ADB.
28
29
Parameters:
30
- serial: Device serial number. If None, auto-detects device.
31
32
Returns:
33
Device instance for automation
34
35
Raises:
36
ConnectError: If device connection fails
37
"""
38
```
39
40
Usage examples:
41
42
```python
43
import uiautomator2 as u2
44
45
# Auto-connect to available device
46
d = u2.connect()
47
48
# Connect to specific device by serial
49
d = u2.connect('Q5S5T19611004599')
50
51
# Connect using environment variable ANDROID_SERIAL
52
# export ANDROID_SERIAL=Q5S5T19611004599
53
d = u2.connect()
54
```
55
56
### Device Information
57
58
Access device properties and system information.
59
60
```python { .api }
61
class Device:
62
@cached_property
63
def serial(self) -> str:
64
"""Device serial number"""
65
66
@property
67
def info(self) -> Dict[str, Any]:
68
"""Device information including display size, orientation, package name, etc."""
69
70
def window_size(self) -> Tuple[int, int]:
71
"""Get device screen dimensions (width, height)"""
72
```
73
74
Usage examples:
75
76
```python
77
d = u2.connect()
78
79
# Get device serial
80
print(d.serial) # e.g., "Q5S5T19611004599"
81
82
# Get comprehensive device info
83
info = d.info
84
print(info)
85
# {'currentPackageName': 'com.android.launcher', 'displayHeight': 1920,
86
# 'displayWidth': 1080, 'screenOn': True, 'sdkInt': 27, ...}
87
88
# Get screen dimensions
89
width, height = d.window_size()
90
print(f"Screen: {width}x{height}")
91
```
92
93
### Device State Control
94
95
Control device power state and screen orientation.
96
97
```python { .api }
98
class Device:
99
def screen_on(self):
100
"""Turn device screen on"""
101
102
def screen_off(self):
103
"""Turn device screen off"""
104
105
@property
106
def orientation(self) -> str:
107
"""Get device orientation: 'natural', 'left', 'right', 'upsidedown'"""
108
109
@orientation.setter
110
def orientation(self, value: str):
111
"""Set device orientation"""
112
113
def freeze_rotation(self, freezed: bool = True):
114
"""Freeze or unfreeze screen rotation"""
115
```
116
117
Usage examples:
118
119
```python
120
d = u2.connect()
121
122
# Screen control
123
d.screen_on()
124
d.screen_off()
125
126
# Orientation control
127
print(d.orientation) # e.g., "natural"
128
d.orientation = "left" # Rotate to landscape
129
d.freeze_rotation(True) # Prevent rotation
130
d.freeze_rotation(False) # Allow rotation
131
```
132
133
### Configuration and Settings
134
135
Configure device behavior and automation settings.
136
137
```python { .api }
138
class Device:
139
@property
140
def settings(self) -> Settings:
141
"""Device settings configuration"""
142
143
def implicitly_wait(self, seconds: Optional[float] = None) -> float:
144
"""Set/get default wait timeout for UI elements"""
145
146
class Settings:
147
def __getitem__(self, key: str) -> Any:
148
"""Get setting value"""
149
150
def __setitem__(self, key: str, value: Any):
151
"""Set setting value"""
152
```
153
154
Available settings:
155
- `wait_timeout`: Default timeout for UI element waiting (default: 20.0)
156
- `operation_delay`: Tuple of (before, after) delays for operations (default: (0, 0))
157
- `operation_delay_methods`: Methods that use operation delay (default: ["click", "swipe"])
158
- `max_depth`: Maximum UI hierarchy depth (default: 50)
159
- `fallback_to_blank_screenshot`: Fallback behavior for screenshots (default: False)
160
161
Usage examples:
162
163
```python
164
d = u2.connect()
165
166
# Configure timeouts
167
d.settings['wait_timeout'] = 10.0
168
d.implicitly_wait(15) # Deprecated, use settings instead
169
170
# Configure operation delays
171
d.settings['operation_delay'] = (0.5, 1.0) # 0.5s before, 1.0s after
172
173
# Configure UI hierarchy depth
174
d.settings['max_depth'] = 30
175
```
176
177
### Logging Configuration
178
179
Configure logging output for debugging and monitoring.
180
181
```python { .api }
182
def enable_pretty_logging(level=logging.DEBUG):
183
"""
184
Enable formatted logging output.
185
186
Parameters:
187
- level: Logging level (DEBUG, INFO, WARNING, ERROR)
188
"""
189
```
190
191
Usage examples:
192
193
```python
194
import uiautomator2 as u2
195
import logging
196
197
# Enable debug logging
198
u2.enable_pretty_logging(logging.DEBUG)
199
200
# Enable info logging
201
u2.enable_pretty_logging(logging.INFO)
202
```