Android Runonuithread Explanation

Runnable, Thread, RunOnUIThread

Most of the code you write runs on the UI thread, ie main thread, by default. Some operations about Views 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



Leave a reply



Submit