Communicating with the UI Thread with Handlers
Every app has its own special thread that runs UI objects such as
View
objects; this thread is called the UI thread. Only objects running on the UI thread have access to other objects on that thread. Because tasks that you run on a thread from a thread pool aren't running on your UI thread, they don't have access to UI objects. To move data from a background thread to the UI thread, use a Handler
that's running on the UI thread
Define a Handler on the UI Thread
Handler
is part of the Android system's framework for managing threads. A Handler
object receives messages and runs code to handle the messages. Normally, you create a Handler
for a new thread, but you can also create a Handler
that's connected to an existing thread. When you connect a Handler
to your UI thread, the code that handles messages runs on the UI thread.
Instantiate the
Handler
object in the constructor for the class that creates your thread pools, and store the object in a global variable. Connect it to the UI thread by instantiating it with the Handler(Looper)
constructor. This constructor uses a Looper
object, which is another part of the Android system's thread management framework. When you instantiate a Handler
based on a particular Looper
instance, the Handler
runs on the same thread as the Looper
. For example:private PhotoManager() { ... // Defines a Handler object that's attached to the UI thread mHandler = new Handler(Looper.getMainLooper()) { ...
Inside the
Handler
, override the handleMessage()
method. The Android system invokes this method when it receives a new message for a thread it's managing; all of the Handler
objects for a particular thread receive the same message. For example: /*
* handleMessage() defines the operations to perform when
* the Handler receives a new Message to process.
*/
@Override
public void handleMessage(Message inputMessage) {
// Gets the image task from the incoming Message object.
PhotoTask photoTask = (PhotoTask) inputMessage.obj;
...
}
...
}
}
The next section shows how to tell the Handler
to move data.
Comments
Post a Comment