一、AndroidUiAutomation 类 功能简介
功能: 为 Android 设备提供 UI 自动化操作的工具类,支持连接设备、获取截图、点击、滑动、获取屏幕分辨率和清理资源等功能。
参数:
device_id(可选):
设备 ID(如 “emulator-5554”),如果未指定则自动检测。
异常:
ConnectionError:
如果无法连接设备。
说明:
AndroidUiAutomation 类基于 uiautomator2 库与 Android 设备交互,提供了一系列方法来执行常见的 UI 操作,适用于 UI 测试和自动化任务。
二、代码功能解析
1. __init__
方法
**功能:**初始化
AndroidUiAutomation
类并连接设备。参数:
device_id(可选)
:设备 ID(字符串类型)。
代码片段:
def __init__(self, device_id=None): try: self.device = u2.connect(device_id) if device_id else u2.connect() print(f"成功连接设备: {self.device.device_info}") except Exception as e: raise ConnectionError(f"无法连接设备: {e}")
说明:
如果提供了
device_id
,则连接指定设备;否则,自动检测并连接设备。连接失败时抛出
ConnectionError 异常
。
2. get_screenshot
方法
**功能:**获取设备屏幕的实时截图,并可选择保存到文件。
参数:
save_path
(可选):保存截图的路径(字符串类型),如果为 None 则不保存。
返回值:
numpy.ndarray:
OpenCV 格式的截图(BGR 格式)。
异常:
Exception:
如果截图失败。
代码片段:
def get_screenshot(self, save_path=None): try: screenshot = self.device.screenshot(format='opencv') if save_path: cv2.imwrite(save_path, screenshot) print(f"截图已保存到: {save_path}") return screenshot except Exception as e: raise Exception(f"获取截图失败: {e}")
说明:
返回设备的实时截图(OpenCV 格式)。
如果指定了
save_path
,则保存截图到该路径。
3. click
方法
**功能:**点击设备屏幕上的指定坐标。
参数:
x:X 坐标(整数类型)。
y:Y 坐标(整数类型)。
返回值:
bool:
操作是否成功。
异常:
ValueError:
如果坐标无效或超出屏幕范围。
代码片段:
def click(self, x, y): try: width, height = self.device.window_size() if not (0 <= x < width and 0 <= y < height): raise ValueError(f"坐标 ({x}, {y}) 超出屏幕范围 {width}x{height}") self.device.click(x, y) print(f"成功点击坐标 ({x}, {y})") return True except Exception as e: print(f"点击失败: {e}") return False
说明:
- 检查坐标是否在屏幕范围内,若有效则执行点击操作并返回 True,否则返回 False。
4. swipe_coordinates
方法
**功能:**在设备屏幕上从起始坐标滑动到结束坐标。
参数:
start_x:
起始点 X 坐标(整数类型)。start_y:
起始点 Y 坐标(整数类型)。end_x:
结束点 X 坐标(整数类型)。end_y:
结束点 Y 坐标(整数类型)。duration(可选):
滑动时长(毫秒,默认为 500ms)。
返回值:
bool:
操作是否成功。
异常:
ValueError:
如果坐标无效或超出屏幕范围。
代码片段:
def swipe_coordinates(self, start_x, start_y, end_x, end_y, duration=500): try: width, height = self.device.window_size() if not (0 <= start_x < width and 0 <= start_y < height and 0 <= end_x < width and 0 <= end_y < height): raise ValueError(f"坐标超出屏幕范围 {width}x{height}") self.device.swipe(start_x, start_y, end_x, end_y, duration) print(f"成功从 ({start_x}, {start_y}) 滑动到 ({end_x}, {end_y}),时长 {duration}ms") return True except Exception as e: print(f"滑动失败: {e}") return False
说明:
- 检查坐标有效性后执行滑动操作,返回操作结果。
5. get_screen_resolution
方法
**功能:**获取设备屏幕的分辨率。
返回值:
tuple:
屏幕分辨率(width, height)。
代码片段:
def get_screen_resolution(self): try: width, height = self.device.window_size() print(f"屏幕分辨率: {width}x{height}") return width, height except Exception as e: print(f"获取分辨率失败: {e}") return None, None
说明:
- 返回屏幕的宽度和高度,失败时返回 (None, None)。
6. cleanup 方法
**功能:**清理资源,断开设备连接。
返回值:
bool:
操作是否成功。
代码片段:
def cleanup(self): try: self.device.disconnect() print("设备连接已断开") return True except Exception as e: print(f"清理失败: {e}") return False
清理资源,断开设备连接
- 断开设备连接并释放资源,返回操作结果。
UiAutomation
类
**功能:**根据系统和语言初始化 UI 自动化操作,并提供模拟操作步骤的方法。
参数:
**system:**操作系统类型(字符串类型,如 “android”)。
**language:**语言类型(字符串类型,如 “en”)。
说明:
UiAutomation
类设计为根据系统和语言配置初始化 UI 操作环境,并通过simulation_operation_step
方法执行具体操作步骤。
1. __init__
方法
**功能:**初始化
UiAutomation
类。参数:
system:
操作系统类型(字符串类型)。language:
语言类型(字符串类型)。
代码片段:
def __init__(self, system, language): if system == "android": # self.drive = AndroidUiAutomation() print(f"system: {system}, language: {language}") # self.action = UITools(self.drive, language)
说明:
根据
system
判断操作系统类型,当前仅支持 “android”。self.drive
和self.action
被注释掉,仅打印系统和语言信息。注意:初始化逻辑不完整,建议启用并完善相关代码。
2. simulation_operation_step
方法
**功能:**根据步骤执行 UI 操作。
参数:
step:
操作步骤(字典类型,包含 “type”、“action” 和 “value” 键)。keywords(可选):
操作关键词列表(默认为 [“type”, “action”, “value”])。
代码片段:
def simulation_operation_step(self, step, keywords=None): if keywords is None: keywords = ["type", "action", "value"] type = step[keywords[0]] # 识别方法:文字识别/图片识别 action = step[keywords[1]] # 操作方法:点击/输入/滑动 value = step[keywords[2]] # 数据 if type in ["text", "ocr", "文本"]: if action in ["click", "点击"]: # self.action.click_text(value) print(f"text: {value}") elif type in ["image", "图片"]: if action in ["click", "点击"]: # self.action.click_image(value) print(f"image: {value}") else: raise ValueError("不支持的操作类型")
说明:
根据 step 中的 type 和 action 执行操作,支持文本识别(“text”、“ocr”、“文本”)和图片识别(“image”、“图片”)。
当前仅支持点击操作,实际操作被注释掉,仅打印信息。
注意:需实现 self.action 的相关方法以完成功能。
三、思路总结
核心思路:
模块化设计:
AndroidUiAutomation
类封装了设备交互的基本操作(如连接、截图、点击、滑动),基于 uiautomator2 实现。UiAutomation
类负责根据系统和语言初始化环境,并提供操作步骤的执行接口。
灵活的操作支持:
支持通过文本识别和图片识别定位 UI 元素,并执行点击等操作。
simulation_operation_step 方法设计为可扩展,支持更多操作类型(如输入、滑动)。
异常处理和资源管理:
- AndroidUiAutomation 类中包含了连接错误处理和资源清理功能,确保操作的稳定性和资源释放。
当前实现状态:
UiAutomation 类的核心功能(self.drive 和 self.action)被注释掉,仅打印信息,未实现实际操作。
代码注释表明作者计划集成 AndroidUiAutomation 和 UITools 来完成完整功能,但尚未实现。
改进建议:
完善 UiAutomation 类的初始化逻辑,启用 self.drive 和 self.action。
实现 UITools 中的 click_text 和 click_image 方法,以支持文本和图片识别的点击操作。
💢 扩展 simulation_operation_step 方法,支持更多操作类型(如输入、滑动)。