Wednesday, March 31, 2010

A Simple ProgressBar Tutorial

I came across another ProgressBar tutorial a few days back posted on helloandroid.com, and while it's certainly good enough to get someone started, it doesn't really go into any detail about how your non-ui thread should work, and how it should gracefully handle Activity restarts and what not. It uses a message handler to send notifications to the ui thread, but what if the Activity is paused and the message handler becomes stale?

So I'm taking this as a good opportunity to follow up on my previous Rebel Without A Context post.

The code is fairly short, so I won't go into a line-by-line explanation of it, but the general idea is that you have your own Thread implementation that maintains state, and you pass it from the old activity to the new activity via onRetainNonConfigurationInstance(). Also rather than updating the UI directly by sending a message from the background thread, the UI thread actively polls the background thread every 50 milliseconds with a handler loop, which updates the progress bar as necessary.

With this kind of approach, you can for example, flip orientations back and forth gracefully with no stale handlers or leaky window exceptions.