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

30 篇文章 3 订阅
28 篇文章 4 订阅

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

以下是一个 JavaScript 类,将 adb 相关指令封装成可重用的函数,并提供了一些示例代码和中文注释。

class ADB {
    /*
     * 创建一个 ADB 实例
     * @param {string} adbPath ADB 可执行文件的路径
     * @param {string} deviceID 设备的序列号(可选)
     */
    constructor(adbPath, deviceID) {
        this.adbPath = adbPath;
        this.deviceID = deviceID || "";
    }

    /*
     * 执行 adb 命令
     * @param {string[]} args 命令参数
     * @returns {Promise<string>} 返回命令输出结果的 Promise 对象
     */
    exec(args) {
        return new Promise((resolve, reject) => {
            const childProcess = require("child_process");
            const cmd = `${this.adbPath} ${this.deviceID ? "-s " + this.deviceID : ""} ${args.join(" ")}`;
            childProcess.exec(cmd, (error, stdout, stderr) => {
                if (error) {
                    reject(error);
                } else {
                    resolve(stdout.trim());
                }
            });
        });
    }

    /*
     * 获取设备列表
     * @returns {Promise<string[]>} 返回设备序列号列表的 Promise 对象
     */
    getDeviceList() {
        return this.exec(["devices"]).then((output) => {
            return output
                .split(/\r?\n/)
                .slice(1)
                .filter((line) => line.trim() !== "")
                .map((line) => line.split(/\s+/)[0]);
        });
    }

    /*
     * 安装应用
     * @param {string} apkPath APK 文件的路径
     * @returns {Promise<void>} 返回 Promise 对象
     */
    installApp(apkPath) {
        return this.exec(["install", "-r", apkPath]);
    }

    /*
     * 卸载应用
     * @param {string} packageName 应用包名
     * @returns {Promise<void>} 返回 Promise 对象
     */
    uninstallApp(packageName) {
        return this.exec(["uninstall", packageName]);
    }

    /*
     * 启动应用
     * @param {string} packageName 应用包名
     * @param {string} activityName 应用的 Activity 名称(可选)
     * @returns {Promise<void>} 返回 Promise 对象
     */
    startActivity(packageName, activityName) {
        const args = ["shell", "am", "start", "-n", packageName];
        if (activityName) {
            args.push(`/${activityName}`);
        }
        return this.exec(args);
    }

    /*
     * 关闭应用
     * @param {string} packageName 应用包名
     * @returns {Promise<void>} 返回 Promise 对象
     */
    stopActivity(packageName) {
        return this.exec(["shell", "am", "force-stop", packageName]);
    }

    /*
     * 清除应用数据
     * @param {string} packageName 应用包名
     * @returns {Promise<void>} 返回 Promise 对象
     */
    clearAppData(packageName) {
        return this.exec(["shell", "pm", "clear", packageName]);
    }


    /*

     拍摄照片
     @param {string} outputPath 照片输出路径
     @returns {Promise<void>} 返回 Promise 对象
     */
    takePhoto(outputPath) {
        return this.exec(["shell", "screencap", "-p", outputPath]);
    }


    /*

     获取屏幕分辨率
     @returns {Promise<{ width: number, height: number }>} 返回 Promise 对象,解析出的对象包含屏幕宽度和高度
     */
    getScreenResolution() {
        return this.exec(["shell", "wm", "size"]).then((output) => {
            const match = output.match(/Physical size: (\d+)x(\d+)/);
            if (match) {
                return {
                    width: parseInt(match[1]),
                    height: parseInt(match[2]),
                };
            } else {
                throw new Error("Failed to get screen resolution.");
            }
        });
    }

    /*

     模拟输入事件
     @param {string} type 事件类型
     @param {number} x 横坐标
     @param {number} y 纵坐标
     @returns {Promise<void>} 返回 Promise 对象
     */
    inputEvent(type, x, y) {
        return this.exec(["shell", "input",${type} ${x} ${y}]);
    }

    /*

     模拟滑动手势
     @param {number} startX 起始点横坐标
     @param {number} startY 起始点纵坐标
     @param {number} endX 终点横坐标
     @param {number} endY 终点纵坐标
     @param {number} duration 滑动时长(单位:毫秒)
     @returns {Promise<void>} 返回 Promise 对象
     */
    swipe(startX, startY, endX, endY, duration) {
        const steps = Math.ceil(duration / 5);
        const swipeArgs = [
            "shell", "input", "swipe",
            startX, startY, endX, endY, steps
        ];
        return this.exec(swipeArgs);
    }

    /*

     设置屏幕亮度
     @param {number} brightness 亮度值(范围:0-255)
     @returns {Promise<void>} 返回 Promise 对象
     */

    setScreenBrightness(brightness) {
        return this.exec([
            "shell",
            "settings",
            "put",
            "system",
            "screen_brightness",
            brightness.toString(),
        ]);
    }

    /*

     获取屏幕亮度
     @returns {Promise<number>} 返回 Promise 对象,解析出的值为屏幕亮度(范围:0-255)
     */
    getScreenBrightness() {
        return this.exec([
            "shell",
            "settings",
            "get",
            "system",
            "screen_brightness",
        ]).then((output) => {
            const match = output.match(/\d+/);
            if (match) {
                return parseInt(match[0]);
            } else {
                throw new Error("Failed to get screen brightness.");
            }
        });
    }

    /*

     设置屏幕超时时间
     @param {number} timeout 超时时间(单位:毫秒)
     @returns {Promise<void>} 返回 Promise 对象
     */
    setScreenTimeout(timeout) {
        return this.exec([
            "shell",
            "settings",
            "put",
            "system",
            "screen_off_timeout",
            timeout.toString(),
        ]);
    }

    /*

     获取屏幕超时时间
     @returns {Promise<number>} 返回 Promise 对象,解析出的值为屏幕超时时间(单位:毫秒)
     */
    getScreenTimeout() {
        return this.exec([
            "shell",
            "settings",
            "get",
            "system",
            "screen_off_timeout",
        ]).then((output) => {
            const match = output.match(/\d+/);
            if (match) {
                return parseInt(match[0]);
            } else {
                throw new Error("Failed to get screen timeout.");
            }
        });
    }

    /*

     截屏并保存到指定路径
     @param {string} filePath 图片保存路径
     @returns {Promise<void>} 返回 Promise 对象
     */
    takeScreenshot(filePath) {
        return this.exec(["shell", "screencap", "-p", filePath]);
    }

    /*

     获取当前屏幕旋转角度
     @returns {Promise<number>} 返回 Promise 对象,解析出的值为屏幕旋转角度(0、90、180 或 270)
     */
    getScreenRotation() {
        return this.exec([
            "shell",
            "dumpsys",
            "input",
            "input_configuration",
        ]).then((output) => {
            const match = output.match(/surfaceOrientation=\d+/);
            if (match) {
                return parseInt(match[0].split("=")[1]);
            } else {
                throw new Error("Failed to get screen rotation.");
            }
        });
    }

    /*

     设置当前屏幕旋转角度
     @param {number} rotation 角度(0、90、180 或 270)
     @returns {Promise<void>} 返回 Promise 对象
     */
    setScreenRotation(rotation) {
        return this.exec([
            "shell",
            "settings",
            "put",
            "system",
            "user_rotation",
            rotation.toString(),
        ]);
    }

    /*

     获取电池电量百分比
     @returns {Promise<number>} 返回 Promise 对象,解析出的值为电量百分比
     */
    getBatteryLevel() {
        return this.exec(["shell", "dumpsys",
            "battery"]).then((output) => {
            const match = output.match(/level:\s*(\d+)/);
            if (match) {
                return parseInt(match[1]);
            } else {
                throw new Error("Failed to get battery level.");
            }
        });
    }

    /*

     获取电池状态
     @returns {Promise<string>} 返回 Promise 对象,解析出的值为电池状态("unknown"、"charging"、"discharging"、"not charging" 或 "full")
     */
    getBatteryStatus() {
        return this.exec(["shell", "dumpsys", "battery"]).then((output) => {
            const match = output.match(/status:\s(\w+)/);
            if (match) {
                return match[1];
            } else {
                throw new Error("Failed to get battery status.");
            }
        });
    }

    /*

     获取电池温度
     @returns {Promise<number>} 返回 Promise 对象,解析出的值为电池温度(单位:摄氏度)
     */
    getBatteryTemperature() {
        return this.exec(["shell", "dumpsys", "battery"]).then((output) => {
            const match = output.match(/temperature:\s(\d+)/);
            if (match) {
                return parseInt(match[1]) / 10.0;
            } else {
                throw new Error("Failed to get battery temperature.");
            }
        });
    }

    /*

     获取电池电压
     @returns {Promise<number>} 返回 Promise 对象,解析出的值为电池电压(单位:伏特)
     */
    getBatteryVoltage() {
        return this.exec(["shell", "dumpsys", "battery"]).then((output) => {
            const match = output.match(/voltage:\s(\d+)/);
            if (match) {
                return parseInt(match[1]) / 1000.0;
            } else {
                throw new Error("Failed to get battery voltage.");
            }
        });
    }

    /*

     获取当前网络状态
     @returns {Promise<string>} 返回 Promise 对象,解析出的值为当前网络状态("wifi" 或 "mobile")
     */
    getNetworkType() {
        return this.exec([
            "shell",
            "dumpsys",
            "connectivity",
            "|",
            "grep",
            "ActiveNetworkInfo",
        ]).then((output) => {
            const match = output.match(/type:\s(\w+)/);
            if (match) {
                return match[1] === "WIFI" ? "wifi" : "mobile";
            } else {
                throw new Error("Failed to get network type.");
            }
        });
    }

    /*

     获取当前 Wi-Fi 名称
     @returns {Promise<string>} 返回 Promise 对象,解析出的值为当前 Wi-Fi 名称
     */
    getWifiName() {
        return this.exec(["shell", "dumpsys", "wifi"]).then((output) => {
            const match = output.match(/SSID:\s(.*)/);
            if (match) {
                return match[1];
            } else {
                throw new Error("Failed to get Wi-Fi name.");
            }
        });
    }

    /*

     获取当前 Wi-Fi MAC 地址
     @returns {Promise<string>} 返回 Promise 对象,解析出的值为当前 Wi-Fi MAC 地址
     */
    getWifiMacAddress() {
        return this.exec([
            "shell", "dumpsys",
            "wifi",
        ]).then((output) => {
            const match = output.match(/MAC:\s*(.*)/);
            if (match) {
                return match[1];
            } else {
                throw new Error("Failed to get Wi-Fi MAC address.");
            }
        });
    }

    /*

     获取 CPU 使用率
     @returns {Promise<number>} 返回 Promise 对象,解析出的值为 CPU 使用率(百分比)
     */
    getCpuUsage() {
        return this.exec([
            "shell",
            "top",
            "-n",
            "1",
            "-d",
            "1",
            "|",
            "grep",
            "%CPU",
        ]).then((output) => {
            const match = output.match(/(\d+.\d+)/);
            if (match) {
                return parseFloat(match[1]);
            } else {
                throw new Error("Failed to get CPU usage.");
            }
        });
    }

    /*

     获取内存使用情况
     @returns {Promise<Object>} 返回 Promise 对象,解析出的值为一个对象,包含以下属性:
     total: 系统总内存(单位:字节)
     free: 系统空闲内存(单位:字节)
     used: 系统已用内存(单位:字节)
     */
    getMemoryUsage() {
        return this.exec(["shell", "cat", "/proc/meminfo"]).then((output) => {
            const matchTotal = output.match(/MemTotal:\s(\d+)\skB/);
            const matchFree = output.match(/MemFree:\s*(\d+)\skB/);
            const matchBuffers = output.match(/Buffers:\s*(\d+)\skB/);
            const matchCached = output.match(/Cached:\s*(\d+)\skB/);
            if (matchTotal && matchFree && matchBuffers && matchCached) {
                const total = parseInt(matchTotal[1]) * 1024;
                const free =
                    parseInt(matchFree[1]) * 1024 +
                    parseInt(matchBuffers[1]) * 1024 +
                    parseInt(matchCached[1]) * 1024;
                const used = total - free;
                return {total, free, used};
            } else {
                throw new Error("Failed to get memory usage.");
            }
        });
    }

    /*

     获取存储使用情况
     @param {string} path 存储路径(默认为主存储器根目录)
     @returns {Promise<Object>} 返回 Promise 对象,解析出的值为一个对象,包含以下属性:
     total: 存储总容量(单位:字节)
     free: 存储可用容量(单位:字节)
     used: 存储已用容量(单位:字节)
     */
    getStorageUsage(path = "/storage/emulated/0") {
        return this.exec(["shell", "df", path]).then((output) => {
            const match = output.match(/\S+\s+\d+\s+(\d+)\s+(\d+)\s+\d+\s+\d+\s+./);
            if (match) {
                const total = parseInt(match[1]);
                const free = parseInt(match[2]);
                const used = total - free;
                return {total, free, used};
            } else {
                throw new Error("Failed to get storage usage.");
            }
        });
    }

    /*

     获取电池电量
     @returns {Promise<number>} 返回 Promise 对象,解析出的值为电池电量(百分比)
     */
    getBatteryLevel() {
        return this.exec(["shell", "dumpsys", "battery"]).then((output) => {
            const match = output.match(/level: (\d+)/);
            if (match) {
                return parseInt(match[1]);
            } else {
                throw new Error("Failed to get battery level.");
            }
        });
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

《代码爱好者》

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

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

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

打赏作者

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

抵扣说明:

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

余额充值