What is the difference between the UI thread and a background thread?
Tier: EssentialDifficulty: Easy
The UI thread, also called the main thread, is the one thread the system creates that's allowed to touch View objects, and it's the only one running a Looper from the moment your app starts, pumping the MessageQueue that drives every click, animation, and lifecycle callback. A background thread is any other thread, whether one you create directly or one pulled from a pool, and it can do heavy work but can never touch a View directly.
Thread {
val result = doExpensiveWork() // fine, off the UI thread
// textView.text = result // would crash, wrong thread
runOnUiThread { textView.text = result } // hop back to the UI thread to touch the view
}.start()
Anything that blocks the UI thread for more than a moment, network calls, disk reads, heavy computation, shows up as dropped frames or, past about five seconds, an ANR. That's the entire reason background threads exist, to keep the UI thread free to keep pumping that queue at 60 or more frames a second. The corresponding rule going the other way is that a background thread can never touch a View directly, since the view system isn't thread safe, results have to be handed back to the UI thread through a Handler, runOnUiThread, or withContext(Dispatchers.Main) in coroutines.