Showing posts with label Tip. Show all posts
Showing posts with label Tip. Show all posts

Thursday, May 31, 2012

Using View.post() - Update the UI From a Background Thread

There are a number of ways of updating the UI from a background thread, including using AsyncTask, using a Handler, or simply by calling View.post().  This article will cover the easiest of the 3 approaches which is using View.post()

View.post() accepts a Runnable and as per the javadoc

Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread.
This method can be invoked from outside of the UI thread only when this View is attached to a window.

The use case for this might be something like this.  You have a UI element that you want to be updated periodically and you have a custom Thread that you have created for doing the background work (perhaps managed in the onStart() and onFinish() of the Activity/Fragment lifecycle).  To update the UI, you MUST be on the UI thread, and the easiest way for this to happen is to call post() on a known view.
parentView.post(new Runnable() {
     public void run() {
         performUIUpdate();
     }
});
The above example assumes the parentView is a view reference that you have obtained in the onCreate() and the performUIUpdate() is a method that you have created that will do the UI update.

Again, in many cases, The AsyncTask or Handler is a better choice for this.  But, it's good know that IF you are not using one of those 2 solutions, then this is a very simple way to update the UI and ensure that your update happens on the UI thread.