Junior — Middle
How can task execution be implemented in the background so as not to block the main thread of the program?
sobes.tech AI
Answer from AI
In Android, to perform tasks in the background without blocking the main (UI) thread, several approaches can be used:
- AsyncTask (deprecated, but simple for small tasks).
- HandlerThread or Thread + Handler for creating a background thread.
- ExecutorService for managing a thread pool.
- Coroutine (Kotlin) — a modern and convenient way of asynchronous programming.
- WorkManager — for deferred and periodic tasks that need to run even if the app is closed.
Example using Kotlin Coroutines:
import kotlinx.coroutines.*
fun loadData() {
GlobalScope.launch(Dispatchers.Main) { // Launch on the main thread
val data = withContext(Dispatchers.IO) { // Execute on a background thread
// Long operation, e.g., network fetch
fetchDataFromNetwork()
}
// Update UI with the received data
updateUI(data)
}
}
This approach allows you to avoid blocking the UI and perform heavy operations asynchronously.