Multithreading
Android has one sacred UI thread (aka main thread).
Draw UI
Handle touch input
Run lifecycle callbacks
Block it and the system crashes your app with an ANR.
So the rule is simple:
Heavy work off the main thread
UI updates only on the main thread
Threads in Android
This works, but:
No lifecycle awareness
No easy way back to the main thread
Easy to leak activities
Example
Starting a thread
Runnable
Looper
A Looper turns a thread into something useful.
Without a Looper:
Thread runs
Executes code
Dies
With a Looper:
Thread stays alive
Processes a message queue
Executes tasks one by one
The main thread already has one:
Background threads do not have, you can add one explicitly.
MessageQueue: The Inbox
Each Looper owns a MessageQueue.
It stores:
MessageobjectsRunnables
They’re processed sequentially, FIFO
Handler: Your Messenger Pigeon
A Handler is a bridge:
You post work
It lands in a MessageQueue
The Looper executes it on its thread
Posting to the main thread
Delayed execution
Handler = how you talk to a thread
Looper = keeps the thread alive
MessageQueue = stores work
HandlerThread: Background Thread With a Brain
Creating your own Looper manually is ceremonial process. Android gives you HandlerThread.
Main Thread + Background Thread Communication
Classic pattern:
Do work on background thread
Post result to main thread
Why Not Update UI From Background Thread ?
Because:
UI toolkit is not thread-safe
Race conditions
Half-drawn views
Modern Replacements
1. Executor / ThreadPoolExecutor
For parallel work.
Still need a Handler to go back to main thread.
2. Coroutines (Kotlin)
Structured concurrency
Lifecycle-aware
Fewer leaks
Less boilerplate
Under the hood, it still uses threads and loopers.