adb_kit/
media.rs

1use crate::device::ADB;
2use crate::error::{ADBResult};
3use log::debug;
4
5impl ADB {
6    /// 从设备截图
7    pub fn take_screenshot(
8        &self,
9        device_id: &str,
10        output_path: &str,
11    ) -> ADBResult<()> {
12        // 在设备上截图并保存到临时文件
13        let device_path = "/sdcard/screenshot.png";
14        self.shell(device_id, &format!("screencap -p {}", device_path))?;
15
16        // 下载截图到本地
17        self.pull(device_id, device_path, output_path, None)?;
18
19        // 清理设备上的临时文件
20        self.shell(device_id, &format!("rm {}", device_path))?;
21
22        Ok(())
23    }
24
25    /// 录制设备屏幕
26    ///
27    /// # 参数
28    /// * `device_id` - 设备 ID
29    /// * `output_path` - 本地输出路径
30    /// * `duration_secs` - 录制时长(秒),最大 180 秒
31    /// * `size` - 可选的分辨率,格式 "widthxheight"
32    pub fn record_screen(
33        &self,
34        device_id: &str,
35        output_path: &str,
36        duration_secs: u32,
37        size: Option<&str>,
38    ) -> ADBResult<()> {
39        // 设备上的临时文件路径
40        let device_path = "/sdcard/screen_record.mp4";
41
42        // 构建命令
43        let mut command = format!("screenrecord --time-limit {} ", duration_secs.min(180)); // 最大 180 秒
44
45        // 添加可选的分辨率参数
46        if let Some(resolution) = size {
47            command.push_str(&format!("--size {} ", resolution));
48        }
49
50        // 添加输出路径
51        command.push_str(device_path);
52
53        // 执行录制命令(这将阻塞直到录制完成)
54        self.shell(device_id, &command)?;
55
56        // 下载录制文件到本地
57        self.pull(device_id, device_path, output_path, None)?;
58
59        // 清理设备上的临时文件
60        self.shell(device_id, &format!("rm {}", device_path))?;
61
62        debug!("屏幕录制已保存到 {}", output_path);
63        Ok(())
64    }
65
66    /// 从设备捕获日志
67    pub fn capture_logs(
68        &self,
69        device_id: &str,
70        tag: Option<&str>,
71        priority: &str,
72    ) -> ADBResult<String> {
73        let tag_filter = tag.map_or(String::new(), |t| format!(" {}", t));
74        self.shell(
75            device_id,
76            &format!("logcat -d{} *:{}", tag_filter, priority),
77        )
78    }
79
80    /// 实时查看日志(返回立即执行的命令)
81    pub fn watch_logs(
82        &self,
83        device_id: &str,
84        tag: Option<&str>,
85        priority: &str,
86    ) -> ADBResult<()> {
87        let tag_filter = tag.map_or(String::new(), |t| format!(" {}", t));
88        let command = format!("logcat{} *:{}", tag_filter, priority);
89
90        // 启动不等待的 shell 命令
91        self.shell_no_wait(device_id, &command)
92    }
93
94    /// 清除日志
95    pub fn clear_logs(&self, device_id: &str) -> ADBResult<()> {
96        self.shell(device_id, "logcat -c")?;
97        Ok(())
98    }
99}