js+ adb工具类文件的封装实例,提供多个实例,并且在代码中包含中文注释,在一个类文件中实现
一个基于 JavaScript 和 adb 工具类封装的示例。以下是代码:
class AdbUtil {
/**
* 开启 adb daemon 服务,并连接设备
* @returns {Promise<boolean>} 是否成功连接上设备
*/
static async startServer() {
const result = await this.execute(`start-server`);
return result.includes(`daemon started successfully`);
}
/**
* 关闭 adb daemon 服务
*/
static async killServer() {
await this.execute(`kill-server`);
}
/**
* 执行 adb shell 命令
* @param {*} command 命令字符串
* @returns {Promise<string>} 返回命令执行结果
*/
static async execute(command) {
const { exec } = require('child_process');
return new Promise((resolve, reject) => {
exec(`adb ${command}`, async (error, stdout, stderr) => {
if (error) {
console.error(`执行命令失败: \n${error}`);
reject(error);
} else {
console.log(`adb ${command} => ${stdout}`);
resolve(stdout);
}
});
});
}
/**
* 启动指定应用程序
* @param {*} packageName 应用包名
* @param {*} activityName 应用启动 Activity 名称
*/
static async launchApp(packageName, activityName) {
await this.execute(`shell am start -n "${packageName}/${packageName}.${activityName}"`);
}
/**
* 判断手机是否已连接上计算机
* @returns {Promise<boolean>} 是否连接成功
*/
static async isDeviceConnected() {
const result = await this.execute(`devices`);
const lines = result.split(`\r\n`);
if (lines.length < 2) {
return false;
} else {
return true;
}
}
/**
* 获取屏幕分辨率
* @returns {Promise<{width:number, height: number}>} 返回宽和高
*/
static async getScreenResolution() {
const result = await this.execute(`shell dumpsys display | grep PhysicalDisplayInfo`);
const pattern = /PhysicalDisplayInfo.*?width=(\d+).* height=(\d+)/i;
const matches = result.match(pattern);
let width = null,
height = null;
if (matches && matches.length == 3) {
width = parseInt(matches[1]);
height = parseInt(matches[2]);
}
return { width, height };
}
/**
* 截屏并保存到本地文件
* @param {*} filePath 图像文件本地路径
*/
static async takeScreenshot(filePath) {
await this.execute(`shell screencap -p > /sdcard/screen.png`);
await this.execute(`pull /sdcard/screen.png ${filePath}`);
await this.execute(`shell rm /sdcard/screen.png`);
}
/**
* 安装 APK 文件
* @param {*} apkFile APK 文件路径
*/
static async install(apkFile) {
await this.execute(`install -r ${apkFile}`);
}
/**
* 卸载应用程序
* @param {*} packageName 应用包名
*/
static async uninstall(packageName) {
await this.execute(`uninstall ${packageName}`);
}
}
该工具类中提供了一些与 adb 相关的方法,例如启动/终止 adb daemon 服务、启动应用程序、截图、安装和卸载应用程序等。下面是一个示例用法:
if(await AdbUtil.isDeviceConnected()){
await AdbUtil.startServer();
await AdbUtil.launchApp("com.example.app","MainActivity");
// 获取屏幕分辨率
const resolution = await AdbUtil.getScreenResolution();
console.log(resolution);
// 截图
await AdbUtil.takeScreenshot("C:\\image\\screen.png");
await AdbUtil.install("C:\\apk\\myapp.apk");
await AdbUtil.uninstall("com.example.app");
await AdbUtil.killServer();
}else{
console.log("请链接手机到计算机")
}
该示例代码中首先检查设备是否连接上计算机。如果已连接,它将连接 adb daemon 服务并启动应用程序。然后获取屏幕分辨率并对设备进行截屏。还可以安装/卸载应用程序等。最后关闭 ADB 服务。