Skip to content

UPDATING THE UI FROM A BACKGROUND THREAD ON ANDROID

Whenever it’s needed to perform some heavy/slow task on a mobile application, it’s a good practice to perform that specific operation on the background, using a thread.

So far so good, but sometimes it’s necessary to update the UI from this background thread. If you ever tried to access an UI element from a background thread, you have already noticed that an exception is thrown.

Let’s assume that the method “doSomeHardWork()” does something really heavy and that the method “updateUI()” updates the interface.

Let’s see how can we update the interface from the background thread:

public class YourClass extends Activity {

	private Button myButton;
	
        //create an handler
	private final Handler myHandler = new Handler();
	
	final Runnable updateRunnable = new Runnable() {
        public void run() {
            //call the activity method that updates the UI
            updateUI();
        }
    };

	
	private void updateUI()
	{
	  // ... update the UI		
	}

        private void doSomeHardWork()
        {
             //.... hard work
             
             //update the UI using the handler and the runnable
             myHandler.post(updateRunnable);
  
        }

	private OnClickListener buttonListener = new OnClickListener() {
		public void onClick(View v) {
			new Thread(new Runnable() {	
					
                                doSomeHardWork();
			
			}).start();
		}
	};
}

That’s it. The post method of the Handler allows the runnable to access the UI.

Try it out ;)

Published inMobile development

Be First to Comment

Leave a Reply