Would you like to create your own Live Wallpaper for Android devices? I’ve got something for you. Don’t start from scratch, use template available on GitHub: https://github.com/chiralcode/Android-Live-Wallpaper-Template. It can be easily imported as Eclipse project and you can use it freely in your projects.
First of all, this template uses Canvas to do the drawing. Using Canvas is great for start, because it’s much simpler then learning OpenGL. It is also sufficient for doing most of 2D animations. This is how I’ve created two of my first live wallpapers: “Underwater World” and “Dots & Waves“.
Another feature is the animation thread. All the drawing is performed in a separate thread. This gives more control over the drawing process and does not block UI thread. Animation thread is paused when wallpaper is not visible. Also frames-per-second limit can be easily set, so it won’t drain the battery.
Template contains following classes:
- Wallpaper (extends WallpaperService): responsible for showing the live wallpaper. There will be only one instance which primary task is to create:
- WallpaperEngine (extends WallpaperService.Engine): contains actual implementation of a wallpaper. There can be more then one WallpaperEngine instance at the same time, for example one for wallpaper set on Home Screen and one for Wallpaper Preview screen. In my opinion, no resources should be shared between those instances if you want to avoid problems. Each WallpaperEngine has it’s own AnimationThread. Engine is responsible for managing lifecycle of this thread: pause and resume drawing when wallpaper visibility changes or stop animation completely when engine is being destroyed.
- AnimationThread (extends Thread): separate thread which does all the work. It can be safely paused and resumed. It’s main task is to update and draw the Scene.
- Scene: custom object in which you should do the actual implementation. It has three methods:
- updateSize() which is called from WallpaperEngine.onSurfaceChanged() when wallpaper dimensions have changed (user has rotated the device).
- update() called from AnimationThread
- draw() which is also called from AnimationThread.
Because updateSize() is called from UIThread and update() and draw() from AnimationThread, methods must synchronized as they share the same Scene resources.
In all methods important from the wallpaper lifecycle point of view, I’ve added log messages, so you can easily trace what is called when.
If you have any questions regarding this template, post a comment.