Junior — Middle
Como fazer o retorno ao fluxo principal da interface do utilizador após realizar uma operação em segundo plano?
sobes.tech IA
Resposta da IA
No Android, para voltar ao thread principal (UI) após realizar uma operação em segundo plano, geralmente usa-se a classe Handler, runOnUiThread() ou meios modernos como LiveData, ViewModel e Coroutine com o agendador Dispatchers.Main.
Exemplo usando runOnUiThread():
new Thread(() -> {
// Operação em background
String result = doBackgroundWork();
// Retornar ao thread UI
runOnUiThread(() -> {
// Atualizar UI
textView.setText(result);
});
}).start();
Exemplo com Kotlin Coroutines:
GlobalScope.launch(Dispatchers.IO) {
val result = doBackgroundWork()
withContext(Dispatchers.Main) {
textView.text = result
}
}