hamibot多线程例子是怎样, 例如主线运行时候,第二线程监听弹窗,出现后点确定。怎么写代码?

QP脚本 · 3 天前
第 1 条补充
·
3 天前

如何插入主线程同时运行?给个代码例子。

回答

Hamibot AI
1
· 3 天前

在 Hamibot 中,你可以使用 threads.start() 创建一个后台线程来监听弹窗,并在弹窗出现时点击确定。以下是一个简单的示例代码:

// 文档地址 https://docs.hamibot.com/
threads.start(function () {
    const check = () => {
        let activity = currentActivity().toLowerCase();
        if (activity.indexOf('permission') !== -1) {
            if (
                id('com.android.systemui:id/dialog_title')
                .textContains('Hamibot')
                .exists()
            ) {
                id('android:id/button1').findOnce().click(); // 点击确认按钮
                return;
            }
        }
        setTimeout(check, 500); // 每 500ms 检查一次
    };
    check();
});

if (!requestScreenCapture()) {
    hamibot.exit(); // 权限获取失败时退出
}
threads.shutDownAll(); // 关闭监控线程
sleep(1000); // 等待弹窗消失
// 在下方添加你的主要脚本逻辑
let img = captureScreen();
// 这里继续编写图像处理/自动化操作代码...

这段代码创建了一个后台线程来监控弹窗,如果弹窗出现,就会点击确认按钮。主线程则继续执行其他操作。


补充回答 1

在 Hamibot 中,主线程是脚本默认运行的线程。如果你想在主线程中同时运行其他任务,可以使用 threads.start() 创建一个新线程来执行这些任务。以下是一个示例代码,演示如何在主线程中同时运行一个监听弹窗的任务:

// 文档地址 https://docs.hamibot.com/
// 主线程逻辑
function mainThread() {
    // 在这里添加你的主线程逻辑
    toast("主线程正在运行");
    // 模拟一些操作
    sleep(5000);
    toast("主线程操作完成");
}

// 子线程逻辑,用于监听弹窗
function childThread() {
    const check = () => {
        let activity = currentActivity().toLowerCase();
        if (activity.indexOf('permission') !== -1) {
            if (
                id('com.android.systemui:id/dialog_title')
                .textContains('Hamibot')
                .exists()
            ) {
                id('android:id/button1').findOnce().click(); // 点击确认按钮
                return;
            }
        }
        setTimeout(check, 500); // 每 500ms 检查一次
    };
    check();
}

// 启动子线程
threads.start(childThread);

// 启动主线程
mainThread();

// 如果需要等待子线程完成,可以使用 threads.shutDownAll();
// threads.shutDownAll();

在这个示例中,mainThread 是主线程的逻辑,childThread 是子线程的逻辑,用于监听弹窗。通过 threads.start(childThread) 启动子线程,主线程继续执行 mainThread 的逻辑。你可以根据需要调整线程的逻辑和执行顺序。

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