androidengineers.Book a session
← All interview questions
ThreadBeginner4 min

What is the Main Thread or UI Thread in Android?

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

Mark this when you can explain the answer in your own words.

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow 💚

Keep practising