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:
Never block the Main Thread!
If the main thread is blocked for:
// ❌ 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
// Method 1
if (Looper.myLooper() == Looper.getMainLooper()) {
// On main thread
}
// Method 2
if (Thread.currentThread() == Looper.getMainLooper().thread) {
// 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"
}
App Start → Main Thread Created → Looper.prepareMainLooper()
↓
MessageQueue created
↓
Looper.loop() starts
↓
Processes messages forever
Mark this when you can explain the answer in your own words.
Help fellow developers prepare for interviews
Sharing helps the Android community grow 💚