As Handler
s are used to send Message
s and Runnable
s to a Thread's message queue it's easy to implement event based communication between multiple Threads. Every Thread that has a Looper
is able to receive and process messages. A HandlerThread
is a Thread that implements such a Looper
, for example the main Thread (UI Thread) implements the features of a HandlerThread
.
Handler handler = new Handler();
Handler handler = new Handler(Looper.getMainLooper());
new Thread(new Runnable() {
public void run() {
// this is executed on another Thread
// create a Handler associated with the main Thread
Handler handler = new Handler(Looper.getMainLooper());
// post a Runnable to the main Thread
handler.post(new Runnable() {
public void run() {
// this is executed on the main Thread
}
});
}
}).start();
// create another Thread
HandlerThread otherThread = new HandlerThread("name");
// create a Handler associated with the other Thread
Handler handler = new Handler(otherThread.getLooper());
// post an event to the other Thread
handler.post(new Runnable() {
public void run() {
// this is executed on the other Thread
}
});