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

Android

Android Problem Overview


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

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

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.

Solution 3 - Android

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

Solution 4 - Android

Another difference: post is per View; runOnUiThread is per Activity.

This means it will be possible (in the future?) to do view.getQueue / activity.getQueue and get exactly what you want without your own tracking or filtering code.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexander KulyakhtinView Question on Stackoverflow
Solution 1 - AndroidMByDView Answer on Stackoverflow
Solution 2 - AndroidpareshgoelView Answer on Stackoverflow
Solution 3 - AndroidkabukoView Answer on Stackoverflow
Solution 4 - AndroidPacerierView Answer on Stackoverflow