Junior — Middle
Kuidas saab korraldada andmete edastamist taustprotsessist peamise täitmise niidile?
sobes.tech AI
Vastus AI-lt
In Android, to transfer data from a background thread to the main (UI) thread, several approaches are commonly used:
- Handler: created in the main thread and receives messages or Runnables from the background thread.
- runOnUiThread: method of Activity that allows executing code in the UI thread.
- LiveData: observable entity, whose updates are automatically delivered 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(() -> {
// UI update
textView.setText(result);
});
}).start();