Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Handler do when running a thread?

Tags:

java

android

I'm really confused about this, but when I'm trigging a thread from my SurfaceView, im sending a Handler with the constructor like this

private static Thread thread;

public SurfaceView(Context localContext) {
      //other stuff
      thread = new Thread(mySurfaceHolder, myEngine, this, new Handler());
      //other stuff
}

and in my thread-class I assign a Handler-object with the handler I sent from my view, like this:

    public Thread (SurfaceHolder lHolder,
    Engine lEngine,
    View lView,
    Handler lHandler){

    surfaceHolder = lHolder;
    engine = lEngine;
    view = lView;
    handler = lHandler;

}

So what does this Handler do? I never use it in my thread-class in any ways, so why are the examples on the web still showing me that I should send a handler with the constructor? I can't see the connection.

like image 682
Curtain Avatar asked Feb 14 '26 12:02

Curtain


1 Answers

From the 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.

Usually it is needed to communicate from your threads back to UI in case you need to execute some code which should run strictly on UI thread.

like image 85
Konstantin Burov Avatar answered Feb 16 '26 02:02

Konstantin Burov