Junior — Middle
How can data transfer be organized from a background process to the main execution thread?
sobes.tech AI
Answer from AI
In Android, there are several approaches to pass data from a background thread to the main (UI) thread:
- Handler: created in the main thread and receives messages or Runnables from the background.
- runOnUiThread: an Activity method that allows executing code on the UI thread.
- LiveData: an observable entity that automatically delivers updates to the UI.
- ViewModel + Coroutine with Dispatchers.Main: coroutines enable switching between threads.
Example with Handler:
Handler mainHandler = new Handler(Looper.getMainLooper());
new Thread(() -> {
// Background work
String result = "Data from background thread";
mainHandler.post(() -> {
// Update UI
textView.setText(result);
});
}).start();