python adb滑动安卓手机全部代码
时间: 2025-05-27 09:08:15 浏览: 17
<think>好的,我现在需要帮用户获取使用Python和ADB实现安卓手机滑动操作的完整代码示例。用户之前已经问过相关问题,我之前也给出过一些代码,但用户现在希望得到更完整的示例。我需要结合之前的回答和用户提供的引用内容,整理出一个全面的代码示例。
首先,回顾用户提供的引用内容。引用[1]提到了使用Python和ADB控制手机,特别是自动触摸和动作。引用[2]展示了如何通过adb.client库连接设备。用户的需求是完整的滑动操作代码,所以需要涵盖连接设备、基础滑动、动态适配分辨率、百分比滑动、进阶方法(如uiautomator2)以及错误处理。
接下来,我需要整合之前的回答中的代码,确保各部分功能完整,并且添加必要的注释和说明。例如,之前提到的adb_swipe函数、获取屏幕分辨率、百分比滑动,以及使用uiautomator2的方法都需要包含进去。
还要考虑用户可能需要的错误处理,比如设备连接失败、权限问题等。此外,是否需要添加设备连接检查的步骤?引用[2]中的代码示例展示了如何检测设备,所以应该包含这部分,确保代码的健壮性。
另外,用户可能希望代码可以直接运行,所以需要确保所有依赖和步骤都明确,比如安装adb工具、启用USB调试、安装必要的Python库(如ppadb和uiautomator2)。
需要检查之前的回答是否有遗漏的部分,比如长滑动优化和滑动轨迹验证,这些在特殊场景处理中提到过,应该包含在完整示例中,或者作为附加功能提供。
最后,确保代码结构清晰,分步骤说明每个部分的功能,比如设备连接、基础滑动函数、动态适配、进阶方法,以及使用示例。同时,添加注意事项,帮助用户避免常见问题,比如USB调试未开启、设备未授权等。
总结步骤:
1. 设备连接与检查
2. 基础滑动函数封装
3. 动态获取分辨率适配不同设备
4. 百分比滑动实现通用性
5. 使用uiautomator2进行更精准的控制
6. 错误处理和常见问题解决
7. 完整代码示例整合
8. 添加必要的注释和使用说明</think>#### 一、完整代码实现(Python + ADB滑动操作)
```python
# -*- coding: utf-8 -*-
import subprocess
from ppadb.client import Client as AdbClient
# ----------------- 基础工具模块 -----------------
class ADBController:
def __init__(self):
self.client = None
self.device = None
def connect_device(self):
""" 连接ADB设备 """
try:
self.client = AdbClient(host="127.0.0.1", port=5037)
devices = self.client.devices()
if not devices:
raise RuntimeError("未检测到ADB设备")
self.device = devices[0]
print(f"已连接设备:{self.device.serial}")
return True
except Exception as e:
print(f"连接失败:{str(e)}")
return False
def get_screen_size(self):
""" 获取屏幕分辨率 """
output = self.device.shell("wm size")
return tuple(map(int, output.split()[-1].split('x'))) # (width, height)
def swipe(self, x1, y1, x2, y2, duration=300):
""" 核心滑动方法
:param duration: 滑动持续时间(毫秒)
"""
try:
# 使用adbkit-python原生方法
self.device.input_swipe(x1, y1, x2, y2, duration)
print(f"滑动成功:({x1},{y1}) → ({x2},{y2})")
return True
except Exception as e:
print(f"滑动失败:{str(e)}")
return False
# ----------------- 高级功能模块 -----------------
class SmartSwiper(ADBController):
def swipe_by_ratio(self, start_ratio, end_ratio, duration=300):
""" 比例滑动(适配任意分辨率)
:param start_ratio: (x_ratio, y_ratio) 起始点比例
:param end_ratio: (x_ratio, y_ratio) 终点比例
"""
width, height = self.get_screen_size()
x1 = int(width * start_ratio[0])
y1 = int(height * start_ratio[1])
x2 = int(width * end_ratio[0])
y2 = int(height * end_ratio[1])
return self.swipe(x1, y1, x2, y2, duration)
def vertical_swipe(self, direction='up', distance_ratio=0.6):
""" 垂直滑动
:param direction: up/down
:param distance_ratio: 滑动距离占屏幕高度的比例
"""
width, height = self.get_screen_size()
y_start = height * 0.8 if direction == 'up' else height * 0.2
y_end = y_start - (height * distance_ratio) if direction == 'up' else y_start + (height * distance_ratio)
return self.swipe(width//2, y_start, width//2, y_end)
# ----------------- 使用示例 -----------------
if __name__ == '__main__':
controller = SmartSwiper()
if controller.connect_device():
# 基础滑动(绝对坐标)
controller.swipe(500, 1600, 500, 800) # 快速滑动
# 比例滑动(屏幕中央向上滑动60%高度)
controller.swipe_by_ratio((0.5, 0.8), (0.5, 0.2))
# 智能垂直滑动
controller.vertical_swipe('up', 0.5) # 向上滑动半屏
# 输出设备信息
print(f"当前分辨率:{controller.get_screen_size()}")
```
#### 二、关键功能说明
1. **设备连接**
使用`ppadb`库建立ADB连接,自动检测已连接的设备[^2]
2. **动态分辨率适配**
`get_screen_size`方法实时获取设备分辨率,确保不同设备兼容性
3. **三种滑动模式**
- 绝对坐标滑动(精确控制)
- 比例坐标滑动(自适应屏幕)
- 智能垂直滑动(简化常见操作)
4. **错误处理机制**
所有操作包含try-except块,避免程序异常退出
#### 三、环境准备步骤
1. 安装依赖库
```bash
pip install ppadb uiautomator2
```
2. 手机端设置
- 开启开发者模式
- 启用USB调试
- 允许模拟点击(MIUI需额外开启「安全设置」)
3. 电脑端配置
- 安装[Android Platform Tools](https://developer.android.com/studio/releases/platform-tools)
- 添加adb到系统PATH
#### 四、进阶优化建议
1. **滑动速度公式**
滑动距离与持续时间的数学关系:
$$ duration = \sqrt{(x_2-x_1)^2 + (y_2-y_1)^2} \times 0.8 $$
可根据实际需求调整系数
2. **轨迹验证方案**
```python
def validate_swipe():
before = cv2.imread('before.png')
controller.swipe(...)
after = cv2.imread('after.png')
diff = cv2.absdiff(before, after)
return np.sum(diff) > threshold # 判断画面变化是否达标
```
3. **多设备控制**
扩展`ADBController`支持同时操作多个设备:
```python
def connect_multiple(self):
return [device.serial for device in self.client.devices()]
```
---
相关问题:
1. 如何通过ADB获取安卓手机实时屏幕坐标?
2. 滑动操作在不同安卓系统版本上有何差异?
3. 如何实现带有曲线轨迹的ADB滑动操作?
[^1]: ADB官方文档
[^2]: Android开发者指南
阅读全文
相关推荐


















