@afjs/adb-sdk
v1.0.0
Published
A lightweight ADB SDK for Node.js
Readme
ADB SDK
一个轻量级、类型安全的 Android Debug Bridge (ADB) SDK,专为 Node.js 环境设计。提供完整的 ADB 功能封装,支持设备管理、文件传输、应用安装、性能监控等功能。
特性
- 🚀 完整的 ADB 功能:支持设备连接、文件传输、应用管理等所有常用 ADB 操作
- 📱 设备信息获取:获取详细的设备系统信息、硬件信息、性能数据
- 🔧 类型安全:完整的 TypeScript 类型定义,提供优秀的开发体验
- ⚡ 异步支持:基于 Promise 的现代异步 API
- 🛡️ 错误处理:完善的错误处理和超时机制
- 📊 性能监控:实时获取 CPU、内存、GPU、电池等性能数据
- 🎯 易于使用:简洁的 API 设计,支持链式调用
- 🧪 测试覆盖:完整的单元测试覆盖
安装
npm install @afjs/adb-sdk或使用 yarn:
yarn add @afjs/adb-sdk或使用 pnpm:
pnpm add @afjs/adb-sdk前置要求
- Node.js >= 16.0.0
- 系统中已安装 ADB 工具
- Android 设备已开启 USB 调试或网络 ADB
安装 ADB
macOS (使用 Homebrew):
brew install android-platform-toolsUbuntu/Debian:
sudo apt-get install android-tools-adbWindows: 下载 Android SDK Platform Tools 并添加到系统 PATH。
快速开始
基础用法
import { AdbClient, AdbService, createAdbClient } from '@afjs/adb-sdk';
// 创建 ADB 客户端
const client = createAdbClient({
host: 'localhost',
port: 5037,
timeout: 30000
});
// 或者使用高级服务类
const service = new AdbService();
// 检查 ADB 是否可用
const isAvailable = await client.isAvailable();
console.log('ADB 可用:', isAvailable);
// 获取设备列表
const devicesResult = await client.listDevices();
if (devicesResult.success) {
console.log('连接的设备:', devicesResult.devices);
}设备连接
// 连接网络设备
const connectResult = await client.connect('192.168.1.100:5555');
if (connectResult.success) {
console.log('设备连接成功');
}
// 设置设备为 TCP/IP 模式
await client.tcpip('device_id', 5555);
// 断开设备连接
await client.disconnect('192.168.1.100:5555');执行 Shell 命令
// 执行简单命令
const result = await client.shell('ls /sdcard', 'device_id');
if (result.success) {
console.log('命令输出:', result.output);
}
// 获取设备属性
const prop = await client.getProperty('ro.build.version.release');
console.log('Android 版本:', prop.output);
// 获取多个属性
const props = await client.getProperties([
'ro.product.manufacturer',
'ro.product.model',
'ro.build.version.release'
]);文件传输
// 推送文件到设备
const pushResult = await client.push(
'/local/path/file.txt',
'/sdcard/file.txt',
'device_id'
);
// 从设备拉取文件
const pullResult = await client.pull(
'/sdcard/file.txt',
'/local/path/file.txt',
'device_id'
);应用管理
// 安装 APK
const installResult = await client.install('/path/to/app.apk', 'device_id', {
replace: true,
grantPermissions: true
});
// 卸载应用
const uninstallResult = await client.uninstall('com.example.app', 'device_id');高级功能
设备信息获取
const service = new AdbService();
// 获取完整设备信息
const deviceInfo = await service.getDeviceInfo('device_id');
if (deviceInfo.success) {
const info = deviceInfo.deviceInfo!;
console.log('设备基本信息:', info.basic);
console.log('系统信息:', info.system);
console.log('显示信息:', info.display);
console.log('内存信息:', info.memory);
console.log('CPU 信息:', info.cpu);
console.log('电池信息:', info.battery);
console.log('网络信息:', info.network);
}性能监控
// 获取实时性能数据
const perfResult = await service.getPerformanceInfo('device_id');
if (perfResult.success) {
const perf = perfResult.performanceInfo!;
console.log('CPU 使用率:', perf.cpu.usage + '%');
console.log('内存使用率:', perf.memory.usage + '%');
console.log('GPU 使用率:', perf.gpu.usage + '%');
console.log('电池电量:', perf.battery.level + '%');
console.log('CPU 温度:', perf.cpu.temperature + '°C');
}端口转发
// 设置端口转发
await client.forward('tcp:8080', 'tcp:8080', 'device_id');
// 反向端口转发
await client.reverse('tcp:9090', 'tcp:9090', 'device_id');设备重启
// 重启设备
const rebootResult = await client.reboot('device_id');
if (rebootResult.success) {
console.log('设备重启命令已发送');
}API 参考
AdbClient
主要的 ADB 客户端类,提供底层 ADB 操作。
构造函数
new AdbClient(options?: AdbClientOptions)配置选项
interface AdbClientOptions {
host?: string; // ADB 服务器地址,默认 'localhost'
port?: number; // ADB 服务器端口,默认 5037
timeout?: number; // 命令超时时间,默认 30000ms
}主要方法
| 方法 | 描述 | 返回类型 |
|------|------|----------|
| isAvailable() | 检查 ADB 是否可用 | Promise<boolean> |
| startServer() | 启动 ADB 服务 | Promise<AdbConnectionResult> |
| killServer() | 停止 ADB 服务 | Promise<AdbConnectionResult> |
| restartServer() | 重启 ADB 服务 | Promise<AdbConnectionResult> |
| listDevices() | 获取设备列表 | Promise<AdbListDevicesResult> |
| connect(address) | 连接网络设备 | Promise<AdbConnectionResult> |
| disconnect(address) | 断开设备连接 | Promise<AdbConnectionResult> |
| tcpip(deviceId?, port?) | 设置 TCP/IP 模式 | Promise<AdbConnectionResult> |
| usb(deviceId?) | 设置 USB 模式 | Promise<AdbConnectionResult> |
| shell(command, deviceId?) | 执行 Shell 命令 | Promise<AdbShellResult> |
| push(local, remote, deviceId?) | 推送文件 | Promise<AdbConnectionResult> |
| pull(remote, local, deviceId?) | 拉取文件 | Promise<AdbConnectionResult> |
| install(apk, deviceId?, options?) | 安装 APK | Promise<AdbConnectionResult> |
| uninstall(package, deviceId?) | 卸载应用 | Promise<AdbConnectionResult> |
| forward(local, remote, deviceId?) | 端口转发 | Promise<AdbConnectionResult> |
| reverse(remote, local, deviceId?) | 反向端口转发 | Promise<AdbConnectionResult> |
| reboot(deviceId?) | 重启设备 | Promise<AdbConnectionResult> |
| getProperty(prop, deviceId?) | 获取设备属性 | Promise<AdbShellResult> |
| getProperties(props, deviceId?) | 获取多个属性 | Promise<AdbShellResult> |
| dumpsys(service, args?, deviceId?) | 执行 dumpsys | Promise<AdbShellResult> |
AdbService
高级服务类,提供更便捷的设备管理功能。
主要方法
| 方法 | 描述 | 返回类型 |
|------|------|----------|
| connect(deviceIP) | 连接设备 | Promise<AdbServiceResult> |
| listDevices() | 获取设备列表 | Promise<AdbServiceResult> |
| executeShell(cmd, deviceIP?) | 执行命令 | Promise<AdbServiceResult> |
| disconnect(deviceIP) | 断开连接 | Promise<AdbServiceResult> |
| restartServer() | 重启服务 | Promise<AdbServiceResult> |
| reconnectDevice(deviceIP) | 重连设备 | Promise<AdbServiceResult> |
| getDeviceInfo(deviceId?, useCache?) | 获取设备信息 | Promise<DeviceInfoResult> |
| getPerformanceInfo(deviceId?) | 获取性能信息 | Promise<DevicePerformanceResult> |
| installApk(apk, deviceId?, options?) | 安装应用 | Promise<AdbServiceResult> |
| uninstallApp(package, deviceId?) | 卸载应用 | Promise<AdbServiceResult> |
| pushFile(local, remote, deviceId?) | 推送文件 | Promise<AdbServiceResult> |
| pullFile(remote, local, deviceId?) | 拉取文件 | Promise<AdbServiceResult> |
| rebootDevice(deviceId?) | 重启设备 | Promise<AdbServiceResult> |
AdbUtils
工具类,提供底层 ADB 命令执行和解析功能。
静态方法
| 方法 | 描述 | 返回类型 |
|------|------|----------|
| setAdbPath(path) | 设置 ADB 路径 | void |
| getAdbPath() | 获取 ADB 路径 | string |
| execute(args, timeout?) | 执行 ADB 命令 | Promise<AdbExecuteResult> |
| executeSimple(args) | 执行简单命令 | Promise<string> |
| parseDevices(output) | 解析设备列表 | AdbDevice[] |
| escapeShellArg(arg) | 转义 Shell 参数 | string |
| checkAdbAvailable() | 检查 ADB 可用性 | Promise<boolean> |
| wait(ms) | 等待指定时间 | Promise<void> |
类型定义
设备信息类型
interface AdbDevice {
id: string;
state: 'device' | 'offline' | 'unauthorized' | 'host' | 'recovery' | 'rescue' | 'sideload' | 'bootloader' | 'unknown';
product?: string;
model?: string;
device?: string;
features?: string[];
}
interface DeviceInfo {
basic: {
deviceId: string;
serialNumber: string;
state: AdbDevice['state'];
};
system: DeviceSystemInfo;
display: DeviceDisplayInfo;
memory: DeviceMemoryInfo;
cpu: DeviceCpuInfo;
battery: DeviceBatteryInfo;
network: DeviceNetworkInfo;
lastUpdated: Date;
}性能信息类型
interface DevicePerformanceInfo {
cpu: {
usage: number; // CPU 使用率 (%)
frequency: number; // CPU 频率 (MHz)
temperature: number; // CPU 温度 (°C)
cores: number; // CPU 核心数
loadAverage: number; // 负载平均值
};
memory: {
total: number; // 总内存 (MB)
used: number; // 已用内存 (MB)
available: number; // 可用内存 (MB)
usage: number; // 内存使用率 (%)
swapTotal: number; // 总交换空间 (MB)
swapUsed: number; // 已用交换空间 (MB)
swapAvailable: number; // 可用交换空间 (MB)
};
gpu: {
usage: number; // GPU 使用率 (%)
frequency: number; // GPU 频率 (MHz)
temperature: number; // GPU 温度 (°C)
memoryTotal: number; // GPU 总内存 (MB)
memoryUsed: number; // GPU 已用内存 (MB)
memoryAvailable: number; // GPU 可用内存 (MB)
};
battery: {
level: number; // 电池电量 (%)
temperature: number; // 电池温度 (°C)
voltage: number; // 电池电压 (mV)
health: string; // 电池健康状态
status: string; // 充电状态
};
timestamp: Date; // 数据采集时间
}结果类型
interface AdbConnectionResult {
success: boolean;
message: string;
error?: Error;
}
interface AdbShellResult {
success: boolean;
output?: string;
error?: Error;
}
interface AdbServiceResult {
success: boolean;
message?: string;
error?: Error | string;
devices?: AdbDevice[];
result?: string;
}错误处理
SDK 提供了完善的错误处理机制:
try {
const result = await client.connect('192.168.1.100:5555');
if (!result.success) {
console.error('连接失败:', result.message);
if (result.error) {
console.error('错误详情:', result.error.message);
}
}
} catch (error) {
console.error('意外错误:', error);
}常见错误类型
- 连接超时:设备无响应或网络问题
- 设备未授权:设备未允许 USB 调试
- ADB 不可用:系统未安装 ADB 或路径配置错误
- 命令执行失败:ADB 命令返回非零退出码
最佳实践
1. 错误处理
// 总是检查操作结果
const result = await client.listDevices();
if (!result.success) {
console.error('获取设备列表失败:', result.error?.message);
return;
}
// 使用 try-catch 处理异常
try {
await client.shell('some-command');
} catch (error) {
console.error('命令执行异常:', error);
}2. 设备管理
// 在操作前检查设备状态
const devices = await client.listDevices();
const targetDevice = devices.devices?.find(d => d.state === 'device');
if (!targetDevice) {
throw new Error('没有可用的设备');
}3. 性能优化
// 使用缓存避免频繁获取设备信息
const service = new AdbService();
const deviceInfo = await service.getDeviceInfo('device_id', true); // 使用缓存
// 设置合适的超时时间
const client = new AdbClient({ timeout: 60000 }); // 60秒超时4. 资源清理
// 在应用结束时清理资源
process.on('exit', async () => {
await client.killServer();
});示例项目
设备监控工具
import { AdbService } from '@afjs/adb-sdk';
class DeviceMonitor {
private service = new AdbService();
private monitoring = false;
async startMonitoring(deviceId: string) {
this.monitoring = true;
while (this.monitoring) {
try {
const perfResult = await this.service.getPerformanceInfo(deviceId);
if (perfResult.success) {
const perf = perfResult.performanceInfo!;
console.log(`CPU: ${perf.cpu.usage}%, 内存: ${perf.memory.usage}%, 电池: ${perf.battery.level}%`);
}
await new Promise(resolve => setTimeout(resolve, 5000)); // 5秒间隔
} catch (error) {
console.error('监控错误:', error);
break;
}
}
}
stopMonitoring() {
this.monitoring = false;
}
}
// 使用示例
const monitor = new DeviceMonitor();
monitor.startMonitoring('192.168.1.100:5555');批量应用安装
import { AdbService } from '@afjs/adb-sdk';
import { readdir } from 'fs/promises';
import { join } from 'path';
async function batchInstallApks(apkDirectory: string, deviceId: string) {
const service = new AdbService();
try {
const files = await readdir(apkDirectory);
const apkFiles = files.filter(file => file.endsWith('.apk'));
console.log(`找到 ${apkFiles.length} 个 APK 文件`);
for (const apkFile of apkFiles) {
const apkPath = join(apkDirectory, apkFile);
console.log(`正在安装: ${apkFile}`);
const result = await service.installApk(apkPath, deviceId, {
replace: true,
grantPermissions: true
});
if (result.success) {
console.log(`✓ ${apkFile} 安装成功`);
} else {
console.error(`✗ ${apkFile} 安装失败:`, result.message);
}
}
} catch (error) {
console.error('批量安装失败:', error);
}
}更新日志
[1.0.0] - 2024-11-03
新增
- 完整的 ADB 客户端实现
- 设备信息获取功能
- 性能监控功能
- 文件传输支持
- 应用管理功能
- 完整的 TypeScript 类型定义
- 单元测试覆盖
许可证
本项目采用 MIT 许可证。
相关链接
注意: 本 SDK 需要系统中已安装 ADB 工具。请确保 ADB 在系统 PATH 中可用,或使用 AdbUtils.setAdbPath() 设置自定义路径。
