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

后端 未结 4 1933
粉色の甜心
粉色の甜心 2020-12-04 11:09

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

相关标签:
4条回答
  • 2020-12-04 11:24

    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.

    0 讨论(0)
  • 2020-12-04 11:32

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

    0 讨论(0)
  • 2020-12-04 11:36

    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.

    0 讨论(0)
  • 2020-12-04 11:40

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

    0 讨论(0)
提交回复
热议问题