Runnable, Thread, RunOnUIThread
Most of the code you write runs on the UI thread, ie main thread, by default. Some operations about View
s must be executed on the UI thread. And operations which consume lots of resources should be executed off the UI thread.
You can start a new Thread
by calling new Thread(Runnable).start()
, then the task will be executed on a non-UI thread. But it's recommended to use a thread pool like ExecutorService
to do this, because it reuses the threads.
For an AsyncTask
, the code in doInBackground()
runs on a non-UI thread from a static thread pool of AsycTask
, while onPostExecuted()
are executed on the UI thread. So you should do UI operations in onPostExecuted()
.
When using Handler
, where the handleMessage()
code runs is based on the Looper
you pass to the constructor of Handler
. By default, it's Looper.getMainLooper()
, so it runs on the UI thread.
Android: What's the difference between Activity.runOnUiThread and View.post?
There is no real difference, except that the View.post
is helpful when you don't have a direct access to the activity.
In both cases, if not on UI thread, Handler#post(Runnable)
will be called behind the scenes.
As CommonsWare mentioned in the comment, there is a difference between the two - when called on Ui thread, Activity#runOnUiThread
will call the run
method directly, while View#post
will post the runnable
on the queue (e.g. call the Handler#post
)
The important point IMO is that both have the same goal, and for whoever use it, there should be no difference (and the implementation may change in the future).
Android runOnUiThread execution sequence
runOnUiThread:
Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.
Activity onCreate()
method also runs in UI thread. First runOnUiThread
code will run then rest of the code.
Related Topics
Eclipse Reports Rendering Library More Recent Than Adt Plug-In
Customize Android Intent.Action_Send
Designing an Android Tablet-Only App
Android Vpnservice to Capture Packets Won't Capture Packets
Add Padding on View Programmatically
Buildconfig.Debug Always False When Building Library Projects with Gradle
How to Use Mapview in Android Using Google Map V2
Java.Lang.Noclassdeffounderror:Failed Resolution of :Lorg/Apache/Http/Protocolversion
How to Click or Tap on a Textview Text
Add Floating Point Value to Android Resources/Values
How to Debug APK Signed for Release
How to Set the Divider Between Tabs in Tablayout of Design Support Library
How to Use Autocompletetextview and Populate It with Data from a Web API
Implementing a Rich Text Editor in Android
Android Download Manager Completed
Adding Ripple Effect to Recyclerview Item