JavaScript应用实例-adb相关指令封装成一个类文件,附上各种实例,各个函数加上中文注释

  • Post author:
  • Post category:java


JavaScript应用实例-adb相关指令封装成一个类文件,附上各种实例,各个函数加上中文注释

以下代码是一个封装了adb相关指令的JavaScript类文件,包括了各种实例和各个函数均添加了中文注释。

const { exec } = require('child_process');

class ADB {
  constructor(serial = null) {
    this.serial = serial;
  }

  // 执行adb相关指令
  async runCmd(command, args = []) {
    const cmd = `adb ${this.serial ? `-s ${this.serial}` : ''} ${command} ${args.join(' ')}`;
    const { stdout, stderr } = await exec(cmd);
    if (stderr) {
      throw new Error('执行adb命令出错:', stderr);
    }
    return stdout.trim();
  }

  // 获取手机品牌
  async getDeviceBrand() {
    return this.runCmd('shell', ['getprop', 'ro.product.brand']);
  }

  // 获取手机型号
  async getDeviceType() {
    return this.runCmd('shell', ['getprop', 'ro.product.model']);
  }

  // 获取android系统版本
  async getAndroidVersion() {
    return this.runCmd('shell', ['getprop', 'ro.build.version.release']);
  }

  // 获取adb连接的设备列表
  async getDeviceList() {
    const devices = await this.runCmd('devices');
    return devices
      .split(/\n/)
      .slice(1)
      .filter((line) => line.trim() !== '')
      .map((line) => {
        const [serial, state] = line.trim().split(/\s+/);
        return { serial, state };
      });
  }

  // 安装apk文件
  async installApk(apkPath, options = {}) {
    const args = ['install'];
    if (!options.allowTestPackages) {
      args.push('-i', 'com.android.defcontainer');
    }
    if (!options.replace) {
      args.push('-r');
    }
    args.push(apkPath);
    try {
      await this.runCmd(...args);
      return true;
    } catch (error) {
      if (/INSTALL_FAILED_ALREADY_EXISTS/.test(error.message)) {
        return false;
      }
      throw error;
    }
  }

  // 卸载应用程序
  async uninstall(packageName) {
    try {
      await this.runCmd('uninstall', [packageName]);
      return true;
    } catch (error) {
      return false;
    }
  }

  // 清除应用程序缓存
  async clearCache(packageName) {
    return this.runCmd('shell', ['pm', 'clear', packageName]);
  }

  // 打开应用程序
  async openApp(packageName, activityName) {
    return this.runCmd('shell', ['am', 'start', '-n', `${packageName}/${activityName}`]);
  }

  // 关闭应用程序
  async closeApp(packageName) {
    return this.runCmd('shell', ['am', 'force-stop', packageName]);
  }

  // 截屏
  async screenshot(filePath) {
    return this.runCmd('shell', ['screencap', '-p', filePath]);
  }

  // 录制屏幕
  async screenRecord(filePath, options = {}) {
    const args = ['shell', 'screenrecord', filePath];
    if (options.resolution) {
      args.push('--size', options.resolution);
    }
    if (options.bitRate) {
      args.push('--bit-rate', options.bitRate);
    }
    if (options.timeLimit) {
      args.push('--time-limit', options.timeLimit);
    }
    if (options.verbose) {
      args.push('--verbose');
    }
    return this.runCmd(...args);
  }
}

module.exports = ADB;

使用实例




const ADB = require('./ADB');

// 实例化adb对象
const adb = new ADB();

// 获取设备列表
adb.getDeviceList().then((devices) => {
  console.log(devices);
});

// 获取当前设备品牌和型号
adb.getDeviceBrand().then((brand) => {
  adb.getDeviceType().then((type) => {
    console.log(`当前设备:${brand} ${type}`);
  });
});

// 安装应用
adb.installApk('apk_path').then((result) => {
  console.log(`安装成功:${result}`);
});

// 卸载应用
adb.uninstall('com.example.app').then((result) => {
  console.log(`卸载成功:${result}`);
});

// 清除应用程序缓存
adb.clearCache('com.example.app').then((result) => {
  console.log(`清除应用程序缓存:${result}`);
});

// 打开应用
adb.openApp('com.example.app', 'com.example.app.MainActivity').then((result) => {
  console.log(`打开应用:${result}`);
});

// 关闭应用
adb.closeApp('com.example.app').then((result) => {
  console.log(`关闭应用:${result}`);
});

// 截屏
adb.screenshot('/path/to/screenshot.png').then((result) => {
  console.log(`截屏成功:${result}`);
});

// 录制屏幕
adb.screenRecord('/path/to/screenrecord.mp4').then((result) => {
  console.log(`录制屏幕成功:${result}`);
});



版权声明:本文为zh6526157原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。