🚀 Enrollments Open for Jetpack Compose Cohort 3 — 4 Weeks of Live Learning to Build Modern Android UIs 💚Join Now
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

  1. Main thread has a Looper that runs an infinite loop
  2. Handler posts messages/runnables to main thread's queue
  3. Never perform I/O, network, or heavy computation on main thread
  4. Use appropriate threading mechanisms for background work
  5. Always update UI only from the main thread

Want to master these concepts?

Join our live cohorts and build production-ready Android apps.

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

Limited slots available each month