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.

Saturday, March 20, 2010

HTTP Connections revisited

In a previous post entitled, HTTP connection reuse in android, I tossed out a code snippet for an HttpClientFactory that would spit out a DefaulHttpClient implementation suitably configured for re-using already open HTTP connections to serve multiple requests across multiple threads.

My hasty implementation from that post leaves a few things to be desired. Primarily, it's a singleton implementation which can lead to some problems. Since it's effectively a global resource, doing things like modifying the time out value, or forcibly closing the connection manager (as one commenter pointed out), could lead to the HttpClient to be in an invalid or undesired state when reused at a different time or a different part of your application.

So here's a simplified version without the singleton garbage:


The ideal place to use something like this is when you want to download multiple items from a single remote source, for example, if I needed to download a bunch of thumbnails to be displayed in a ListView, I could have a thread pool downloading images concurrently and all sharing this one HttpClient instance, reusing HTTP connections as they became available (all managed inside the HttpClient)