Curtain
Curtain

Reputation: 1972

What does Handler do when running a thread?

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.

Upvotes: 3

Views: 6452

Answers (3)

Brad Hein
Brad Hein

Reputation: 11047

Just define your handler in the main activity, as a global.

Handler mUIHandler = new Handler();

And now you can post to the mUIHandler immediately and it always goes to your UI thread.

Upvotes: 2

Konstantin Burov
Konstantin Burov

Reputation: 69228

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.

Upvotes: 5

JRL
JRL

Reputation: 77995

I assume in your code you are extending Thread, because there is no constructor taking a handler for the Thread class. The handler is used to communicate back to the UI thread, as the Android threading model requires UI operations to be performed on a special dedicated thread.

When creating a new thread, the code is executed in a background thread, and thus UI-operations are unsafe. If you do not need to do anything UI-related, you can remove the handler.

Since Android API 3, there is AsyncTask, which makes communication between background and UI easier and alleviates the need to use a handler.

Examples:

  • For an example of using a Handler, see this.
  • See Painless Threading as well, which contains links to sample projects using threading.

Upvotes: 4

Related Questions