HandlerThreads and communication between Threads
suggest changeHandlers send Messages and Runnables to a thread’s message queue, so they can carry events between threads. A thread can receive those messages when it has a Looper. The main thread has a Looper, and it is not a HandlerThread. HandlerThread is a separate class that prepares a Looper for a background thread.
Creating a Handler for the current Thread
Handler handler = new Handler();
Creating a Handler for the main Thread (UI Thread)
Handler handler = new Handler(Looper.getMainLooper());
Send a Runnable from another Thread to the main Thread
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();
Creating a Handler for another HandlerThread and sending events to it
// create another Thread
HandlerThread otherThread = new HandlerThread("name");
otherThread.start(); // getLooper() blocks until the thread has started
// 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
}
});
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents