Notes from Erik Hellman’s talk about “Fast, user-friendly and power-efficient network communication on Android” on the second day of DroidCon UK 2012.
Doing network communication the right way isn’t all that hard, just keep a couple of recommendations in mind. There is no need to “re-invent the wheel”, other fields have struggled with this problem before, we can learn from them. There are also a lot of open source projects that tackle various network related problems, quite often one of those will meet your requirements.
That being said, handling the network on a mobile phone can be difficult. The connection can drop out of nowhere, the quality can change or you might not even be online at all. There are a couple of things that developers can do to make the experience better:
- HTTP Client handling
- Background network I/O
- Playing server
Generally speaking HttpUrlConnection is the best client to use, except for Eclair and Froyo, for these API versions the Apache HTTP client has fewer bugs.
Make sure to wrap the HttpUrlConnection streams in buffers and always exhaust the streams.
Enable caching, it will save a lot of network traffic.
To avoid blocking the UI thread, always run your network related tasks on a different thread using a Service with a Handler implementation.
If you need to poll a URL on a regular basis, use the AlarmManager to schedule requests at a set (slightly inexact) interval.
An Android device could also serve as a server (think multiplayer gaming). This could be quite complex to create, but luckily the Netty.io library will probably meet most of your needs.
And lastly, don’t use a splash-screen, there should be no need for it. Give the user as much control as possible.