java - Handler 在运行线程时做什么?

标签 java android

我对此真的很困惑,但是当我从我的 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/

相关文章:

java - 使用 spring 3 mvc 框架创建基本表单

android - Android JNI 中的 Cpp 标志 - 根据标志更改变量

android - 尽管我已获得许可,但无法连接到互联网

java - 第一个参数类型错误

java - Android - 获取 Google Places Photos 和 API 调用

java - mxHierarchicalLayout 忽略 isVertexMovable

java - Netbeans 设计器显示的形式与程序运行时不同

java - OGNL 线程安全

java - 如何确保在销毁对象之前调用方法?

java - 从 PHP 返回值到 Java 客户端