Essential Android Handler edit forum

HandlerThreads and communication between Threads

As Handlers are used to send Messages and Runnables 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.

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");

// 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
    }
});

Table Of Contents
39 ACRA
45 Handler
64 Menu
112 Loader
119 Xposed
132 Colors
135 Fresco
140 AdMob
147 Button
156 Vk SDK
170 XMPP
176 OpenCV
200 FileIO
203 Moshi
217 Paint
231 AIDL
241 JCodec
243 Okio
255 Looper
  ↑ ↓ to navigate     ↵ to select     Esc to close