Android 有一个严格的线程模型,围绕主(UI)线程展开——它必须处理 UI 并保持响应性。理解线程、为什么必须将工作移出主线程,以及工具(coroutines 和历史上的 threads/handlers)对响应式应用很重要。
主线程规则
Android has a single MAIN (UI) thread that:
→ handles ALL UI operations (drawing, events) — UI updates MUST happen on it
→ must stay RESPONSIVE — blocking it freezes the UI; >5s blocked = ANR (App Not Responding)
TWO key rules:
1. DON'T do long/blocking work on the main thread (network, DB, heavy compute) → move it off
2. DON'T update UI from a background thread → switch back to the main thread for UI
将工作移出主线程
viewModelScope.launch {
= withContext(Dispatchers.IO) {
repository.fetchData()
}
updateUi()
}
