Handler is the core mechanism for inter-thread communication in Android, used to pass messages between worker threads and the main (UI) thread.
Core Components of Handler
1. Handler
-
Purpose: Send and process messages
-
Features:
- Bound to the Looper of the thread that created it
- Responsible for sending Messages to MessageQueue
- Processes messages distributed by Looper
2. Looper
-
Purpose: Message loop, continuously retrieves messages from MessageQueue
-
Features:
- Each thread can only have one Looper
- Main thread has Looper created by default
- Sub-threads need to call Looper.prepare() and Looper.loop() manually
3. MessageQueue
-
Purpose: Queue for storing messages
-
Features:
- First In First Out (FIFO)
- Sorted by time (when field)
- Implemented using singly linked list
4. Message
-
Purpose: Carrier for data and information
-
Properties:
- what: Message identifier
- arg1/arg2: Integer parameters
- obj: Object parameter
- callback: Runnable callback
Handler Workflow
shellSend message flow: Handler.sendMessage() → MessageQueue.enqueueMessage() → Message enqueued Process message flow: Looper.loop() → MessageQueue.next() → Handler.dispatchMessage() → Handler.handleMessage()
Code Example
java// Main thread Handler Handler mainHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { // Process message, update UI } }; // Sub-thread Handler new Thread(() -> { Looper.prepare(); Handler threadHandler = new Handler() { @Override public void handleMessage(Message msg) { // Process message } }; Looper.loop(); }).start();
Handler Memory Leak
Cause:
- Non-static inner class holds reference to outer Activity
- Delayed messages prevent Activity from being recycled
Solutions:
- Use static inner class + WeakReference
- Remove all messages when Activity is destroyed
- Use Handler's removeCallbacksAndMessages(null)
Key Points
- Main thread Looper is created in ActivityThread.main()
- Difference between Handler.post() and sendMessage()
- Message.obtain() reuses message objects to avoid memory allocation
- IdleHandler executes when message queue is idle