我目前正在使用 Python 中的并发.futures 和 uiautomator2 库来自动化 Android 设备上 WhatsApp 的 UI 交互。在我的场景中,我想自动化发送 WhatsApp 消息的过程。
我有两个使用 future 的独立 UI 交互任务。 一个用于“Send_btn xpath”查找,另一个用于“Ok_btn xpath”查找。
此外,这是肯定的,如果“发送找到的 xpath”,那么“好吧,未来将继续尝试查找”,因为在 Whatsapp 上可以联系,并且测试框中有消息,它将有一个发送 btn 并且没有弹出窗口。
如果找到“好的”,那么“发送未来将继续卡住试图找到”。由于在 Whatsapp 上无法联系,那么它将有可以关闭弹出窗口的 btn,并且没有发送 btn。
现在,我想要的是,如果未来的任何人完成,我也想立即终止其他未来,即使它仍在运行,以减少漫长的等待时间。 但是,我在终止另一项任务时遇到了困难。
如果不可能,请指导我另一个可能的解决方案。
import uiautomator2 as ui2
import concurrent.futures
def decide_event(_xpath, device):
try:
device(resourceId=_xpath).click()
except Exception as e:
print(e)
serial = 'RZ8R31TJ21B'
device = ui2.connect(serial)
PHONE_NUMBER = '91xxxxxxxxxx'
MESSAGE = 'Hello World!'
device.shell(["am", "start", "-a", "android.intent.action.VIEW", "-d", f"https://api.whatsapp.com/send?phone={PHONE_NUMBER}&text={MESSAGE}"])
send_btn = "com.whatsapp:id/conversation_entry_action_button"
okay_btn = "android:id/button1"
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
future_send = executor.submit(decide_event, send_btn, device)
future_okay = executor.submit(decide_event, okay_btn, device)`
我尝试了
Event.set()
不幸的是它没有成功。不确定我是否以正确的方式实施了它。
这里有一个建议:等待第一个任务完成,然后调用
shutdown
关闭线程池。
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
future_send = executor.submit(decide_event, send_btn, device)
future_okay = executor.submit(decide_event, okay_btn, device)`
concurrent.futures.wait(
[future_send, future_okay],
return_when=concurrent.futures.FIRST_COMPLETED,
)
executor.shutdown(wait=False, cancel=True)
我用我自己的“decide_event”版本尝试了一下,它似乎有效。