importPackage(Packages.okhttp3);
/**
* 获取指定应用的版本号
* @param {string} packageName 应用包名
*/
function getPackageVersion(packageName) {
    importPackage(android.content);
    var pckMan = context.getPackageManager();
    var packageInfo = pckMan.getPackageInfo(packageName, 0);
    return packageInfo.versionName;
}
/**
 * 时间转秒数
 * @param {string} timeStr 时间格式的字符串 10:05:32
 */
function timeToSec(timeStr) {
    var s = '';
    var time_array = timeStr.split(':');
    if (time_array.length == 3) {
        var hour = time_array[0];
        var min = time_array[1];
        var sec = time_array[2];
        s = Number(hour * 3600) + Number(min * 60) + Number(sec);
        return s;
    };
    if (time_array.length == 2) {
        var min = time_array[0];
        var sec = time_array[1];
        s = Number(min * 60) + Number(sec);
        return s;
    };
};
/**
* 抖音短网址还原
* @param {string} str 短网址
*/
function dy_shortUrl(str) {
    var rst = "";
    var client = new OkHttpClient()
    var request = new Request.Builder().url(str).get().build();
    var res = client.newCall(request).execute();
    rst = res.request().url().toString();
    return rst;
}
function myToast(message) {
    var _toast_ = toast;
    toast = function (message) {
        _toast_(message);
        sleep(2000);
    }
    for (var i = 0; i < 100; i++) {
        toast(i);
    }
};
/**
 * 唤醒手机
 */
function wakeUp() {
    if (!device.isScreenOn()) {
        device.wakeUpIfNeeded();
    }
}
//倒计时悬浮窗
function remind_Win(str, time) {
    threads.start(
        function () {
            var sec = time;
            //悬浮窗口
            var r_Win = floaty.rawWindow(
                <frame w="*" h="*">
                    <card id="load" h="100" w="auto" cardBackgroundColor="#ff000000" layout_gravity="center" cardElevation="0" cardCornerRadius="10dp" alpha="0.7">
                        <frame w="auto" padding="15 0">
                            <frame w="auto" layout_gravity="center">
                                <text id="load_time" text="10" w="auto" h="auto" layout_gravity="center" marginBottom="10" textStyle="bold" textColor="#90ffffff" textSize="20" />
                                <progressbar w="60" h="60" layout_gravity="center" marginBottom="10" alpha="0.8" />
                            </frame>
                            <text id="i_text" text="倒计时" w="auto" h="auto" margin="0 10" layout_gravity="bottom|center" textColor="#90ffffff" textSize="16" />
                        </frame>
                    </card>
                </frame>
            );
            r_Win.setSize(-1, -1);
            r_Win.setTouchable(false);
            while (true) {
                ui.run(function () {
                    r_Win.load_time.setText(String(sec));
                    r_Win.i_text.setText(String(str));
                });
                sleep(1000);
                sec = sec - 1;
                if (sec <= 0) {
                    r_Win.close();
                    break;
                };
            };
        });
    sleep(time * 1000);
};
//加载中悬浮窗
function progress_Win(str) {
    var r_Win = floaty.rawWindow(
        <frame w="*" h="*">
            <card id="load" h="100" w="auto" cardBackgroundColor="#ff000000" layout_gravity="center" cardElevation="0" cardCornerRadius="10dp" alpha="0.7">
                <frame w="auto" padding="15 0">
                    <frame w="auto" layout_gravity="center">
                        <progressbar w="60" h="60" layout_gravity="center" marginBottom="10" alpha="0.8" />
                    </frame>
                    <text id="i_text" text="倒计时" w="auto" h="auto" margin="0 10" layout_gravity="bottom|center" textColor="#90ffffff" textSize="16" />
                </frame>
            </card>
        </frame>
    );
    r_Win.setSize(-1, -1);
    r_Win.setTouchable(false);
    ui.run(function () {
        r_Win.i_text.setText(String(str));
    });
    return r_Win;
};
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
/**
 * 自动请求截屏权限
 */
function auto_RequestScreenCapture() {
    //截图
    var athread = threads.start(function () {
        var beginBtn = classNameContains("Button").textContains("立即开始").findOne(3000);
        if (beginBtn !== null) {
            beginBtn.click();
        }
    });
    if (requestScreenCapture(false)) {
        log("请求截屏权限成功.")
    } else {
        log("请求截屏权限失败.")
    };
};
/**
 * 截屏,返回截图后的图片路径
 */
function capture() {
    log("函数capture开始")
    //截图
    // var athread = threads.start(function () {
    //     var beginBtn = classNameContains("Button").textContains("立即开始").findOne(3000);
    //     if (beginBtn !== null) {
    //         beginBtn.click();
    //     }
    // });
    // if (!requestScreenCapture(false)) {
    //     toastLog("请求截图失败");
    //     exit();
    // }
    // sleep(1000);
    var im = captureScreen();
    var picName = "Screenshots_" + new Date().Format("yyyyMMdd_hhmmss_") + currentPackage() + ".png";
    var path = "/sdcard/Pictures/Screenshots/" + picName;
    files.ensureDir(path);
    console.log(picName);
    //保存图片
    im.saveTo(path);
    if (files.exists(path)) {
        log("截图存在:" + picName);
        media.scanFile(path);
        sleep(1000);
        log("函数capture结束")
        return path;
    } else {
        log("截图不存在:" + picName);
    }
};
/**
* 打开QQ群名片
* @param {string} qqGroupNum QQ群号
*/
function addQQun(qqGroupNum) {
    app.startActivity({
        action: "android.intent.action.VIEW",
        data: "mqqapi://card/show_pslcard?card_type=group&uin=" + qqGroupNum,
        packageName: "com.tencent.mobileqq",
    });
};
function readDeviceInfo() {
    console.log("设备屏幕宽度: " + device.width);
    console.log("设备屏幕高度: " + device.height);
    console.log("修订版本号: " + device.buildId);
    console.log("主板型号: " + device.broad);
    console.log("厂商品牌: " + device.brand);
    console.log("工业设计名称: " + device.device);
    console.log("设备型号: " + device.model);
    console.log("整个产品名称: " + device.product);
    console.log("Bootloader版本: " + device.bootloader);
    console.log("硬件名称: " + device.hardware);
    console.log("唯一标识码: " + device.fingerprint);
    console.log("硬件序列号: " + device.serial);
    console.log("AndroidAPI版本: " + device.sdkInt);
    console.log("Incremental: " + device.incremental);
    console.log("Android系统版本号: " + device.release);
    console.log("BaseOS: " + device.baseOS);
    console.log("安全补丁程序级别: " + device.securityPatch);
    console.log("开发代号: " + device.codename);
    console.log("AndroidId: " + device.getAndroidId());
    console.log("Mac地址: " + device.getMacAddress());
    console.log("内存总量: " + device.getTotalMem());
    console.log("当前可用内存: " + device.getAvailMem());
};
/**
* 打开QQ片
* @param {string} qqNum QQ号
*/
function addQQ(qqNum) {
    app.startActivity({
        action: "android.intent.action.VIEW",
        data: "mqqapi://card/show_pslcard?card_type=person&uin=" + qqNum,
        packageName: "com.tencent.mobileqq",
    });
};
// 卸载APP
function uninstallApp(packageName) {
    shell("pm uninstall " + packageName, true)
};
// 系统是否ROOT
function isRoot() {
    var r = shell("ls /system/bin", true).result.toString()
    if (r.length > 50) {
        return true
    } else {
        return false
    }
};
function PrefixInteger(num, length) {
    return (Array(length).join('0') + num).slice(-length);
}
//秒转时间
function formatSeconds(value) {
    var theTime = parseInt(value);// 需要转换的时间秒
    var theTime1 = 0;// 分
    var theTime2 = 0;// 小时
    var theTime3 = 0;// 天
    if (theTime > 60) {
        theTime1 = parseInt(theTime / 60);
        theTime = parseInt(theTime % 60);
        if (theTime1 > 60) {
            theTime2 = parseInt(theTime1 / 60);
            theTime1 = parseInt(theTime1 % 60);
            if (theTime2 > 24) {
                //大于24小时
                theTime3 = parseInt(theTime2 / 24);
                theTime2 = parseInt(theTime2 % 24);
            }
        }
    }
    var result = '';
    result = PrefixInteger(parseInt(theTime2), 2) + ":" + PrefixInteger(parseInt(theTime1), 2) + ":" + PrefixInteger(parseInt(theTime), 2);  //时
    return result;
}
/**
 * 等待指定的包启动
 * @param {string} packStr 包名
 * @param {boolean} loopRun 是否重复运行
 * @param {inter} timeOut 设置超时时间,为0表示一直等待
 */
function runAndWaitPackage(packStr, loopRun, timeOut) {
    log("函数runAndWaitPackage开始");
    var rst = false;
    var startTime = new Date().getTime();
    var exitTime = startTime + timeOut;
    var curPack = "";
    try {
        app.launchPackage(packStr);
        while (true) {
            //循环运行
            if (loopRun) {
                app.launchPackage(packStr);
            };
            //超时退出
            if (timeOut > 0) {
                if (new Date().getTime() >= exitTime) {
                    log("— — 超时退出");
                    rst = false;
                    break;
                };
            };
            //获取当前包名
            curPack = currentPackage();
            if (curPack == packStr) {
                log("— — 已找到目标包名");
                rst = true;
                break;
            };
            sleep(500);
        };
    } catch (error) {
    } finally {
        log("函数runAndWaitPackage结束");
        return rst;
    };
};
// 关闭应用
function killPackage(PackName) {
    try {
        var appName = app.getAppName(PackName);
        log("结束运行:" + appName);
        app.openAppSetting(PackName);
        var curAct = "";
        while (true) {
            curAct = currentActivity();
            if (curAct.indexOf("settings") >= 0 || curAct.indexOf("MaterialDialog") >= 0 || curAct.indexOf("appmanager") >= 0) {
                break;
            };
        };
        log("进入了应用管理页面");
        text(appName).waitFor();
        var stopBtn = textMatches(/(.*强.*|.*束.*|.*停.*|.*结.*|.*运.*|.*行.*)/).enabled(true).findOne(3000);
        if (stopBtn !== null) {
            log("结束APP按钮可用");
            stopBtn.click();
            sleep(500);
            var a = classNameContains("Button").textMatches(/(.*确.*|.*停.*|.*止.*|.*强.*|.*行.*|.*定.*)/).enabled(true).find();
            if (a !== null) {
                log("再次点击关闭");
                a.click();
                sleep(200);
            };
        } else {
            console.log(appName + " 未运行.");
        };
        while (true) {
            curAct = currentActivity();
            if (curAct.indexOf("settings") >= 0 || curAct.indexOf("MaterialDialog") >= 0 || curAct.indexOf("appmanager") >= 0) {
                console.log("返回");
                back();
                sleep(1000);
            } else {
                break;
            }
        };
        log("killPackage 函数退出");
    } catch (e) {
        console.log("killPackage出错:" + e);
    };
};
function swipeEx(qx, qy, zx, zy, time) {
    var xxy = [time];
    var point = [];
    var dx0 = {
        "x": qx,
        "y": qy
    };
    var dx1 = {
        "x": random(qx - 50, qx + 50),
        "y": random(qy, qy + 200)
    };
    var dx2 = {
        "x": random(zx - 50, zx + 50),
        "y": random(zy, zy + 50),
    };
    var dx3 = {
        "x": zx,
        "y": zy
    };
    for (var i = 0; i < 4; i++) {
        eval("point.push(dx" + i + ")");
    };
    // log(point[3].x)
    for (let i = 0; i < 1; i += 0.08) {
        xxyy = [parseInt(bezier_curves(point, i).x), parseInt(bezier_curves(point, i).y)]
        xxy.push(xxyy);
    }
    // log(xxy);
    gesture.apply(null, xxy);
};
function bezier_curves(cp, t) {
    cx = 3.0 * (cp[1].x - cp[0].x);
    bx = 3.0 * (cp[2].x - cp[1].x) - cx;
    ax = cp[3].x - cp[0].x - cx - bx;
    cy = 3.0 * (cp[1].y - cp[0].y);
    by = 3.0 * (cp[2].y - cp[1].y) - cy;
    ay = cp[3].y - cp[0].y - cy - by;
    tSquared = t * t;
    tCubed = tSquared * t;
    result = {
        "x": 0,
        "y": 0
    };
    result.x = (ax * tCubed) + (bx * tSquared) + (cx * t) + cp[0].x;
    result.y = (ay * tCubed) + (by * tSquared) + (cy * t) + cp[0].y;
    return result;
};
//判断对象是否未定义
function is_Undefined(a) {
    var rst = false;
    if (a == null) {
        rst = true;
    };
    if (typeof (a) == "undefined") {
        rst = true;
    };
    return rst;
}
// 获取指定应用的版本号
function getPackageVersion(packageName) {
    importPackage(android.content);
    var pckMan = context.getPackageManager();
    var packageInfo = pckMan.getPackageInfo(packageName, 0);
    return packageInfo.versionName;
};
// QQ强制聊天
function qqChat(qqNum) {
    app.startActivity({
        action: "android.intent.action.VIEW",
        data: "mqq://im/chat?chat_type=wpa&version=1&src_type=web&uin=" + qqNum,
        packageName: "com.tencent.mobileqq",
    });
};
// 取md5
function getMd5(string) {
    return java.math.BigInteger(1, java.security.MessageDigest.getInstance("MD5").digest(java.lang.String(string).getBytes())).toString(16);
};
// 取随机汉字
function getRndWord() {
    eval("var word=" + '"\\u' + (Math.round(Math.random() * 20901) + 19968).toString(16) + '"')
    return word;
};
// 等待指定的控件出现,并且点击它
function wait_ClickButton(a_uiselector, time, boundClick) {
    var btn = a_uiselector.findOne(time);
    if (btn !== null) {
        if (!boundClick) {
            btn.click();
        } else {
            click(btn.bounds().centerX(), btn.bounds().centerY())
        };
        sleep(800);
    }
};
/**
* 判断指定的UI控件是否存在,支持超时
* @param {string} a_uiselector uiselector
* @param {integer} time 超时时间,单位毫秒
* @param {boolean} inScreen 判断控件是否在屏幕内,默认为false
*/
function uiExists(a_uiselector, time, inScreen) {
    var dw = device.width;
    var dh = device.height;
    var rst = false;
    var btn = a_uiselector.findOne(time);
    if (btn !== null) {
        if (inScreen) {   //判断是不是在屏幕范围内
            if (UIisInScreen(btn)) {
                log("找到控件:" + a_uiselector);
                rst = true;
            } else {
                rst = false;
            }
        } else {
            rst = true;
        };
    };
    return rst;
};
/**
* 获取指定的UI控件,支持超时
* @param {string} a_uiselector uiselector
* @param {integer} time 超时时间,单位毫秒
* @param {boolean} inScreen 判断控件是否在屏幕内,默认为false
*/
function getUI(a_uiselector, time, inScreen) {
    var dw = device.width;
    var dh = device.height;
    var rst = null;
    var btn = a_uiselector.findOne(time);
    if (btn !== null) {
        if (inScreen) {   //判断是不是在屏幕范围内
            var B = btn.bounds();
            if ((B.left >= 0) && (B.left < dw) && (B.right > 0) && (B.right <= dw) && (B.top >= 0) && (B.top < dh) && (B.bottom > 0) && (B.bottom <= dh)) {
                rst = btn;
            };
        } else {
            rst = btn;
        };
    };
    return rst;
};
/**
* 判断指定的控件是不是在屏幕范围内
*/
function UIisInScreen(a) {
    var dw = device.width;
    var dh = device.height;
    var rst = false;
    if (a !== null) {
        var B = a.bounds();
        if ((B.left >= 0) && (B.left < dw) && (B.right > 0) && (B.right <= dw) && (B.top >= 0) && (B.top < dh) && (B.bottom > 0) && (B.bottom <= dh)) {
            rst = true;
        };
    };
    return rst;
}
//利用获取目标控件的矩形区域,进行点击操作
function clickByBounds(a) {
    if (a !== null) {
        click(a.bounds().centerX(), a.bounds().centerY());
        sleep(800);
    }
}
function superClick(obj) {
    if (text(obj).exists()) {
        click(
            text(obj).find()[0].bounds().centerX(),
            text(obj).find()[0].bounds().centerY()
        )
        return true
    }
    else if (desc(obj).exists()) {
        click(
            desc(obj).find()[0].bounds().centerX(),
            desc(obj).find()[0].bounds().centerY()
        )
        return true
    } else if (id(obj).exists()) {
        click(
            id(obj).find()[0].bounds().centerX(),
            id(obj).find()[0].bounds().centerY()
        )
        return true
    } else if (className(obj).exists()) {
        click(
            className(obj).find()[0].bounds().centerX(),
            className(obj).find()[0].bounds().centerY()
        )
        return true
    } else {
        toastLog(obj + ':控件不存在')
        return false
    }
};
//指定的APP包是否存在
function packageIsExists(p) {
    if (getAppName(p) == null) {
        return false;
    } else {
        return true;
    }
};
//机器人自动回复
function robot_Reply(Problem) {
    var apiurl = "https://api.ownthink.com/bot?appid=48ff1c36e81641b196493ad4eab4422b&userid=UI6LAfhI&spoken=" + Problem;
    let client = new OkHttpClient();
    let request = new Request.Builder().url(apiurl).get().build();
    var res = client.newCall(request).execute();
    var aresult = res.body().string();
    var Json = JSON.parse(aresult);
    return Json.data.info.text;
};
/**
 * 随机获取一句古诗
 */
function getRndPl() {
    importPackage(Packages.okhttp3);
    var apiurl = "https://api.77sec.cn/yiyan/api.php";
    let client = new OkHttpClient();
    let request = new Request.Builder().url(apiurl).get().build();
    var res = client.newCall(request).execute();
    var aresult = res.body().string();
    aresult = aresult.split('"')[1];
    aresult = aresult.split('——')[0];
    return aresult;
};
//安装APK
function installApk(apkPath) {
    app.startActivity({
        data: "file://" + apkPath,
        type: "application/vnd.android.package-archive",
        action: "VIEW",
        flags: ["grant_read_uri_permission", "grant_write_uri_permission"]
    });
};
var common = {};
common.addQQun = addQQun;
common.addQQ = addQQ;
common.uninstallApp = uninstallApp;
common.getPackageVersion = getPackageVersion;
common.isRoot = isRoot;
common.getMd5 = getMd5;
common.wait_ClickButton = wait_ClickButton;
common.dy_shortUrl = dy_shortUrl;
common.killPackage = killPackage;
common.getRndWord = getRndWord;
common.formatSeconds = formatSeconds;
common.clickByBounds = clickByBounds;
common.superClick = superClick;
common.packageIsExists = packageIsExists;
common.is_Undefined = is_Undefined;
common.swipeEx = swipeEx;
common.robot_Reply = robot_Reply;
common.uiExists = uiExists;
common.UIisInScreen = UIisInScreen;
common.remind_Win = remind_Win;
common.getUI = getUI;
common.installApk = installApk;
common.progress_Win = progress_Win;
common.readDeviceInfo = readDeviceInfo;
common.wakeUp = wakeUp;
common.capture = capture;
common.auto_RequestScreenCapture = auto_RequestScreenCapture;
common.runAndWaitPackage = runAndWaitPackage;
common.timeToSec = timeToSec;
module.exports = common;

 

发表回复

后才能评论