我对此真的很困惑,但是当我从我的 SurfaceView 触发一个线程时,我会像这样发送一个带有构造函数的处理程序
private static Thread thread;
public SurfaceView(Context localContext) {
//other stuff
thread = new Thread(mySurfaceHolder, myEngine, this, new Handler());
//other stuff
}
在我的线程类中,我用我从 View 发送的处理程序分配了一个处理程序对象,如下所示:
public Thread (SurfaceHolder lHolder,
Engine lEngine,
View lView,
Handler lHandler){
surfaceHolder = lHolder;
engine = lEngine;
view = lView;
handler = lHandler;
}
那么这个Handler是做什么的呢?我从来没有以任何方式在我的线程类中使用它,那么为什么网络上的例子仍然告诉我应该用构造函数发送一个处理程序? 我看不到连接。
最佳答案
来自Handler docs :
When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create. You can create your own threads, and communicate back with the main application thread through a Handler. This is done by calling the same post or sendMessage methods as before, but from your new thread. The given Runnable or Message will than be scheduled in the Handler's message queue and processed when appropriate.
如果您需要执行一些应严格在 UI 线程上运行的代码,通常需要从您的线程与 UI 通信。
关于java - Handler 在运行线程时做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3531423/