Sobes.tech
Junior — Middle

Come tornare al flusso principale dell'interfaccia utente dopo aver eseguito un'operazione in background?

sobes.tech AI

Risposta dell'AI

In Android, per tornare al thread principale (UI) dopo aver eseguito un'operazione in background, si utilizzano generalmente classi come Handler, runOnUiThread() o strumenti moderni come LiveData, ViewModel e Coroutine con il dispatcher Dispatchers.Main.

Esempio con runOnUiThread():

new Thread(() -> {
    // Operazione in background
    String result = doBackgroundWork();

    // Ritorno al thread UI
    runOnUiThread(() -> {
        // Aggiornamento UI
        textView.setText(result);
    });
}).start();

Esempio con Kotlin Coroutines:

GlobalScope.launch(Dispatchers.IO) {
    val result = doBackgroundWork()
    withContext(Dispatchers.Main) {
        textView.text = result
    }
}