Reputation: 40186
To run something in Main thread from other thread we call runOnUiThread()
. Question is, this call is synchronous or asynchronous?
If I want to run something synchronously in main thread, how do I do that?
Upvotes: 1
Views: 1301
Reputation: 1986
It's asynchronous. It returns immediately without waiting for the task you post finished running.
To run something synchronously in main thread:
If your are in the main thread, just run it.
If your are in a different thread. You need some synchronization mechanism. For example, you can use a semaphore. Acquire a semaphore in the background thread, and let the runnable you passed in runOnUiThread to release that semaphore after it finished running. This way your background thread will wait for the runnable. Well, it's still asynchronous in the eyes of the main thread. But it is synchronous in the eyes of the background thread.
Upvotes: 1
Reputation: 17834
You can't "run something asynchronously in the main thread" because that's not how asynchronous logic works. For something to be asynchronous it has to run on a different thread, otherwise it wouldn't, by definition, be asynchronous.
runOnUiThread()
posts the Runnable you pass to the main thread's Handler. It then runs on the main thread at the next available opportunity.
Don't put any heavy logic on the main thread. runOnUiThread()
is used so you can update UI elements, like TextViews or ProgressBars, when something happens in the asynchronous logic.
Upvotes: 3