Pages

Tuesday, March 13, 2012

Moving work off the UI Thread

This is a mistake that I've seen a lot of people make (by which I mean me.)  I can't speak for other platforms, but in both Swing and Android, there is only one thread running the UI.  In other words, while your handler method is running in response to a button press or some other UI action, nothing else is getting done in the interface, including listening for any other input by the user.


That's fine when your handler is only doing small actions in response the user actions.  But if you have to do something that could take several seconds, you should start a new thread to do it so the UI thread can go back to its work.

But where this can really trip you up is an activity that takes an unpredictable amount of time.  Or, more specifically, an activity that usually takes a short time, but could drag on.  Network communications are a place where this can happen: the network may react quickly most of the time, but become congested occasionally.  I imagine many people will be making this mistake in mobile programming.

There are a number of different ways of approaching Threads in Android, which I'll start reviewing in upcoming posts.  The simplest way is to use the traditional Java way: create a class implementing the Runnable interface, then create a Thread object, passing an instance of your Runnable class as a parameter.

You'll find this approach is quite limited because your new thread can't do anything to affect the UI - only the UI's thread can.  So if you want the interface to react to the actions of the background thread, you'll want to try a different approach.