Questions
ThreadBeginner4 min
What is the Main Thread or UI Thread in Android?
Main ThreadUI Thread
Answer
What is the Main Thread?
The Main Thread (also called UI Thread) is the primary thread where your Android app runs. It's created when your app starts and is responsible for:
- UI rendering - Drawing views, layouts, animations
- Event handling - Touch events, clicks, gestures
- Lifecycle callbacks - onCreate(), onResume(), etc.
- System callbacks - BroadcastReceiver, Service callbacks
The Golden Rule
Never block the Main Thread!
If the main thread is blocked for:
- 16ms+ → Dropped frames (jank)
- 5 seconds+ → ANR dialog (Application Not Responding)
What NOT to Do on Main Thread
// ❌ DON'T DO THESE ON MAIN THREAD val data = URL("https://api.example.com").readText() // Network val bitmap = BitmapFactory.decodeFile(path) // Large file I/O database.query("SELECT * FROM users") // Database Thread.sleep(1000) // Blocking
How to Check if on Main Thread
// Method 1 if (Looper.myLooper() == Looper.getMainLooper()) { // On main thread } // Method 2 if (Thread.currentThread() == Looper.getMainLooper().thread) { // On main thread }
How to Run Code on Main Thread
1. From Activity/Fragment
runOnUiThread { textView.text = "Updated" }
2. Using Handler
val mainHandler = Handler(Looper.getMainLooper()) mainHandler.post { textView.text = "Updated" }
3. Using Coroutines (Recommended)
lifecycleScope.launch(Dispatchers.Main) { val data = withContext(Dispatchers.IO) { fetchData() // Background } textView.text = data // Main thread }
4. View.post()
textView.post { textView.text = "Updated" }
Main Thread Looper
App Start → Main Thread Created → Looper.prepareMainLooper()
↓
MessageQueue created
↓
Looper.loop() starts
↓
Processes messages forever
Key Points
- Main thread has a Looper that runs an infinite loop
- Handler posts messages/runnables to main thread's queue
- Never perform I/O, network, or heavy computation on main thread
- Use appropriate threading mechanisms for background work
- Always update UI only from the main thread
1:1 Mentorship
Get personalized guidance from a Google Developer Expert. Accelerate your career with dedicated support.
Personalized Learning Path
Mock Interviews & Feedback
Resume & Career Guidance
Share & Help Others
Help fellow developers prepare for interviews
Sharing helps the Android community grow 💚