Junior — Middle
How to ensure the execution of certain actions in the main thread from another thread?
sobes.tech AI
Answer from AI
In Android, to perform actions on the main (UI) thread from another thread, you can use the Handler class or runOnUiThread.
Example using runOnUiThread in an Activity:
runOnUiThread(new Runnable() {
@Override
public void run() {
// Code to be executed on the main thread
textView.setText("Updated from another thread");
}
});
You can also use a Handler associated with the main thread's Looper:
Handler mainHandler = new Handler(Looper.getMainLooper());
mainHandler.post(new Runnable() {
@Override
public void run() {
// Actions on the main thread
}
});
In modern applications, architectural components and coroutines are often used, but these methods are standard for basic understanding.