Since version 2.1, Android has had a live wallpaper feature which allows dynamic wallpapers to be built for the Android home screen that can animate and respond to touch and other inputs. They’re remarkably easy to develop so I spent some of my time off this holiday season building one I call Neon Trails. The wallpaper draws little trails that wind themselves across the screen and around each other.
The algorithm for the trails is relatively simple, each moves forward one unit and then chooses a random direction to travel in before moving forward another unit and picking another direction. Each trail won’t pick a direction that will cause it to overlap with itself or another and will stop moving as soon as is it gets trapped.
The rendering was done using the 2D API that Android provides via the Canvas class. The little lights at the end of active trails were achieved by faking a bloom effect by repeatedly rendering a circle with a number of BlurMaskFilters, each with a smaller radius than the last.
Most of the work was spent optimising various things. A more optimised wallpaper will scroll better as the user drags between virtual home screens and will use less battery. Memory allocation and garbage collection are generally quite expensive on the Dalvik VM so avoiding using the new keyword where ever possible, except on start up, is generally a good idea when optimising for Android (there is still some work to do here as both the Trail and Grid class frequently allocate new Point instances). The DDMS eclipse tool that you get with Android is excellent for tracking these things.
The technique that seemed to give the greatest benefit in terms of performance was generating an offscreen buffer (an instance of Bitmap) to render the “terminated” trails to (active trails are moving too much so would invalidate the buffer on every frame). Referencing the buffer with a SoftReference meant that the system could always garbage collect the image if it couldn’t spare the memory required. This is generally good practice for all non-essential offscreen buffers when working on optimised UIs in Java where memory might be tight.
The wallpaper is fairly customisable in terms of appearance, you can alter the color scheme and appearance of the trails and can even set a lower frame rate if you’re worried about the wallpapers effect on battery life. The wallpaper is available for free on the Android Market and you can find the code on Github.