while(true){
console.log("====")
try{text("确定").findOne().click()}catch(e){console.log(e)}
try{text("确认信息并支付").findOne().click()}catch(e){console.log(e)}
try{text("就是这家").findOne().click()}catch(e){console.log(e)}
try{text("我知道了").findOne().click()}catch(e){console.log(e)}
if(text('确认无误').exists()){
try{className("android.widget.TextView").text('确认无误').findOne().click()}catch(e){console.log(e)}
detectWechatPay()
}
}; 执行第二遍程序卡主了不执行了

已存档
兔如花
9
· 25 天前

回答

Hamibot AI
1
· 25 天前

文档地址 https://docs.hamibot.com/

在你的代码中存在以下潜在问题:

  1. 高频循环阻塞:while(true)循环没有延时,会导致脚本以最大频率执行点击操作,可能触发应用防刷机制或导致UI线程过载。

  2. 上下文依赖风险:当页面跳转时(如进入支付页面),原有控件可能已失效,后续操作会持续失败但未跳出循环。

  3. 函数嵌套隐患detectWechatPay()函数内部若存在阻塞操作(如无限等待支付结果),会导致主循环停滞。


优化方案

while(true){
    console.log("====")
    
    // 添加循环间隔,避免高频触发
    sleep(1000); 
    
    // 优化控件查找逻辑,增加超时机制
    var confirm = text("确定").findOne(1000);
    if(confirm && confirm.clickable()) confirm.click();
    
    var payBtn = text("确认信息并支付").findOne(1000);
    if(payBtn && payBtn.clickable()) payBtn.click();
    
    // 使用组合条件判断减少误触
    var thisStore = text("就是这家").findOnce();
    if(thisStore && thisStore.bounds().height() > 0) thisStore.click();
    
    // 异常处理标准化
    try{
        className("android.widget.Button").text("我知道了").findOne(500).click();
    }catch(e){
        // 记录具体错误
        console.error("跳过按钮异常: " + e.message); 
    }
    
    // 支付检测逻辑优化
    if(text('确认无误').exists()){
        clickConfirmAndHandlePay();
    }
}

// 提取独立函数增强可维护性
function clickConfirmAndHandlePay(){
    try{
        className("android.widget.TextView").text('确认无误').findOne(500).click();
        
        // 启动独立线程处理支付检测
        threads.start(function(){
            // 设置最大等待时间(10秒)
            var payResult = detectWechatPay(10000); 
            console.log("支付检测结果: " + (payResult ? "成功" : "超时"));
        });
        
    }catch(e){
        console.error("确认操作失败: " + e.message);
    }
}

关键改进点

  1. 增加 sleep() 间隔:每轮循环强制暂停1秒,降低资源消耗

  2. 控件存在性检查

    • 使用 findOne(timeout) 设置查找超时时间
    • 添加 clickable()bounds() 检查防止无效点击
  3. 支付检测多线程化

    // 为detectWechatPay添加超时参数
    function detectWechatPay(timeoutMs){
        var startTime = new Date().getTime();
        while(new Date().getTime() - startTime < timeoutMs){
            if(text("支付成功").exists()){
                return true; // 检测到支付成功
            }
            sleep(500); // 降低检测频率
        }
        return false; // 超时返回
    }
    
  4. 错误分类处理

    • 记录具体错误类型(如 clickable() 为 false 时)
    • 不同环节的异常单独捕获

建议在实际运行时监控控制台日志,定位具体卡顿环节。如果问题仍然存在,请提供卡顿时的界面截图和日志输出。

ℹ️ 本回答由 AI 生成,内容仅供参考