Android – Live Wallpaper part 2

March 22nd, 2012 by Paul Gregoire

Let’s make the star that we created in part 1 rotate in just a few simple steps. Although before we start, I’d like to note that we are technically rotating the entire canvas and not just the star itself; adding more than one star to the display will clearly expose this minor detail. I’ve done some research on the rotation of multiple individual items at-once, but I have not yet found a solution that fits; feel free to comment if you are aware of how to accomplish it.

The code modifications below are being in the LiveWallpaper.java source file, we are not using the only other source file GoldstarActivity.java at this time.

1. Add a variable where we keep track of the first frame drawn. This will prevent some calculations from being executed more than once per instance.

2. To rotate the star, we will use degrees. In steps 2 and 3, two methods of generation are shown. In this section we use a float counter for degrees of rotation.

3. In this section we use a fixed array for degrees of rotation. To do so, we also must create an index counter and an array of 360 floats; again, its up-to-you as to which option to use.

4. If using the array method, the onCreate method is modified to pre-fill our array when the application is first initialized.

Note: I’ve tried both methods for degree cycling and they seem equally fast on my device.

4. Modify our drawing code from part 1. The code block is here for reference.

Before

After (using float counter)

After (using float array)

6. As an aside to what we done thus far, you can easily add another star with a couple extra lines like so:

The additional star will be down and to the right of the primary star. This star will not rotate per-se but instead will “orbit” the primary star.

7. Last step, build and run in the emulator. Right click on the goldstar project in Package Explorer and select Run As -> Android Application. If you haven’t created any AVD (virtual devices), you’ll be prompted to create one. Creation of an AVD is covered here.

When everything works, you’ll see this in the Eclipse console:

I recorded the emulator running the apk in this screencast

Running on my Galaxy Nexus

In the sample code, I’ve refactored the original class alittle to make things more clear.
Project Source

End of part two.

, , , ,