gpt4 book ai didi

java - 如何在 Android 中将回调发布到任意线程

转载 作者:行者123 更新时间:2023-11-30 02:32:43 26 4
gpt4 key购买 nike

我使用的是 Unity 游戏引擎,它也支持导出到 Android。

该引擎使用多个线程,包括 UI 线程和一个单独的脚本线程,所有用户自定义代码都在该线程中执行。

我的方案要求我在后台线程中调用一些操作,我想将结果编码回主脚本线程。

我知道 AsyncTask 的基础知识, ExecutorLooper类。其中,Looper 似乎是一个不错的选择,因为它允许设置队列并将消息回发到给定线程(AsyncTask 是“硬连线”以在 UI 线程上运行回调,这不是我想要的)。

实现此目标的正确方法是什么?

最佳答案

与 UI 线程通信主要有 3 种方式:

  1. Activity.runOnUiThread(Runnable)

  2. View.post(Runnable)

  3. Handlers

在你的情况下,我建议你创建一个 Handler,因为前 2 个解决方案意味着你有一个对你的 ActivityView< 的引用

编辑

如果您想在您的应用中使用任何线程,只需确保已设置Looper,并使用关联的Handler

class YourLooperThread extends Thread
{
// make it accessible from the outside
private Handler handler;

@Override public void run()
{
Looper.prepare();

// Customize your handler, it has to be used in any thread which want to push a message in this thread's looper message Queue
handler = new Handler();

Looper.loop();
}
}

小心:您要在该线程中执行的所有其他任务都必须通过消息队列完成,即在处理程序中发布可运行的任务。更多信息:Handlers, MessageQueue, Looper, do they all run on the UI thread?

关于java - 如何在 Android 中将回调发布到任意线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27088175/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com