Android: What's the difference between Activity.runOnUiThread and View.post?

What's the difference between Activity.runOnUiThread and View.post, could someone, please, explain?


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).


Another difference between Activity.runOnUiThread and view.post() is that the runnable in view.post() is called after the view is attached to a window.


Either are acceptable for most situations and for the most part they are interchangeable, but they are subtly different. The biggest difference of course is that one is available from an Activity and the other from a View. There's a lot of overlap between those, but sometimes in an Activity you will not have access to a View, and sometimes in a View you will not have access to an Activity.

One of the edge cases I've encountered with View.post I mentioned in an answer to another SO question on View.post: View.post only works from another thread when the View is attached to a window. This is rarely a problem, but can occasionally cause the Runnable to never execute, especially if you call View.post in the onCreate method of your Activity. An alternative is to use Handler.post which is what Activity.runOnUiThread and View.post use under the covers anyway.

(edited for accuracy, added "from another thread")