Android: Activity.runOnUiThread 和 View.post 有什么区别?

Activity.runOnUiThreadView.post有什么区别,谁能解释一下?

29973 次浏览

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

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 View.post1: View.post only works View.post2 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 View.post3 which is what Activity.runOnUiThread and View.post use under the covers anyway.

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

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.

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.