第五篇 electron + vue + adb 实现与安卓文件交互

本文介绍了如何在Node.js中集成ADB工具,包括执行adb命令、获取设备信息、管理应用、截图、录屏,以及使用node-usb检测USB设备连接,还涉及文件在PC和移动设备之间的读写操作。

1.引入adb环境

将platform-tools放至public目录下,(platform-tools已放顶部附件,可自行下载使用)

2.编写adb常用工具类

这里运行adb命令使用的是node 的 child_process 模块

const { execSync } = require('child_process');
import iconv from "iconv-lite";
import path from "path";

let adbUrl = path.resolve("D:\\platform-tools_r34.0.4-windows\\platform-tools\\adb");
export default {
    constructor(serial = null) {
        this.serial = serial;
    },
    // 执行adb相关指令
    runCmd(command, args = []) {
        const cmd = adbUrl+`${this.serial ? `-s ${this.serial}` : ''} ${command} ${args.join(' ')}`;
        let result ;
        result = execSync(cmd);
        return iconv.decode(result, 'cp936')
    },

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

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

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

    // 获取adb连接的设备列表
     getDeviceList() {
        const devices =  this.runCmd2(' devices');
         let line = devices
         line = line.split('\n');
         var res = new Array();
         if(line.length > 0) {
            for(var i =1; i<line.length; i++) {
                if(line[i]) {
                    var temp = line[i].replace(/(^\s*)|(\s*$)/g, "");
                    if(temp) {

                        if(line[i].split('\t')[1].indexOf("offline") != -1){

                            return "offline"

                        }
                        res[i-1] = line[i].split('\t')[0];
                    }
                }
            }
        }
        return res

    },

    // 安装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);
    }
}

3.检测移动设备接入与拔出

一开始使用的是 node-usb 来检测USB端口的热插拔

安装 

npm install usb

使用

var usb = require('usb')

//检测设备接入
usb.on('attach', function(device) { 
});


//检测设备移除
usb.on('detach', function(device) { 
});

但是发现和adb状态不一致,,并且不太稳定,所以换了方案,前端采用定时器实时检测设备,引入2中的工具类,adb.getDeviceList

<script>
import adb from "../utils/adb"
export default {
 data() {
    return {
        timer:null
    }
}
 mounted() {
    this.getPhone();
  },
  methods: {
    getPhone(){
      this.timer = setInterval(()=>{
        this.findPhone();
      },2000)
    },
    findPhone() {
       let devices = adb.getDeviceList()
      if(devices == "offline"){
        this.$message({
            message: '数据传输通道异常中断,请检查,重新连接!',
            type: 'warning'
          });
        return
      }else{
        //在线

      }

    }
   }

}
</script>

4.文件读取与写入

移动设备路径一般是 /sdcard/*

4.1 将文件从pc写入移动设备
adb push 电脑路径 手机路径
4.2 将文件从移动设备写入pc
adb pull 手机路径 电脑路径

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@Moment

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值