Junior — Middle
How can a task be launched in a service so that it does not occupy the main execution thread?
sobes.tech AI
Answer from AI
In Android, to prevent a task from blocking the main (UI) thread, it needs to be run in a background thread. You can use:
AsyncTaskclasses (deprecated but still used)ThreadorRunnableHandlerThreadExecutorService- Modern approach — use Kotlin Coroutines or
WorkManagerfor background tasks
Example with Kotlin Coroutines:
GlobalScope.launch(Dispatchers.IO) {
// Long operation, e.g., loading data
val data = loadData()
withContext(Dispatchers.Main) {
// Update UI after completion
updateUI(data)
}
}
Thus, the main idea is to perform heavy operations outside the main thread so that the interface remains responsive.