Monday, April 5, 2010

Asynchronous HTTP Connections on Android: A Tutorial

Asynchronous HTTP Connections on Android: A Tutorial


For a pleasant Android user experience it is vital for applications to actively provide feedback. When downloading images and data from the web, delays are expected. Developers should implement asynchronous connections and provide active feedback on their progress.

Throttling connections is another important technique. Android phones are mainly on 3G and Edge connections and are prone to slow connection speeds. Imagine downloading 100 images from the web simultaneously at 1 KB/second each. That certainly doesn’t make for the greatest user experience. Executing connections in smaller chunks is a much better option. For example, downloading those 100 images I mentioned earlier in chunks of 5 connections would allow for a comparable 20 KB/second rate.

Below is an example of my asynchronous HTTP connection implementation using the classes HttpConnection and ConnectionManager. It uses Apache’s HttpClient methods and allows for GET, POST, PUT and DELETE requests. A built in Bitmap decoder is also included.

To receive status updates from an HttpConnection a Handler is used (but not required). The HttpConnection will dispatch a message to the Handler at the occurrence of the following:

HttpConnection.DID_START – The connection is removed from the ConnectionManager’s queue and started
HttpConnection.DID_SUCCEED – The connection was successful and the response is stored in the Message instance obj field
HttpConnection.DID_ERROR – The connection failed and the exception is stored in the Message instance obj field

No comments:

Post a Comment