2

For my live wallpaper I use the following code (called by a Runnable) to draw each frame. Each time it is called, I fill the current canvas with a solid color and draw a background bitmap (bg_image has been resized to perfectly fit the screen). I then call drawParticles(c), which simply uses c.drawCircle(...) a bunch of times drawing particles all over the canvas.

In the live wallpaper preview mode, this code works great. However, when I actually set this as my live wallpaper it flickers and seems to not clear the canvas before drawing. Let me 'splain:

Frame 1: The bitmap is drawn and circles are overlaid.

Frame 2: The bitmap is drawn and circles are overlaid (based on my rough understanding, there are two canvases that are drawn on and posted alternately for efficiency).

Frame 3: The canvas is not being cleared! This frame includes the new positions of each drawn circle as well as the circles from Frame 1!.

Frame 4: Includes the new positions of each drawn circle as well as the circles from Frame 2!

The end effect is that the circles leave "trails" all over the screen that flicker between (I believe) the two alternating canvases. Why, based on my code below, isn't my canvas being cleared each frame? Again, this works fine during preview mode but not when it is actually set as my live wallpaper. It's also worth noting that this flickering problem only occurs if I am drawing a bitmap; if the background is just a solid color, this problem never arises.

final SurfaceHolder holder = getSurfaceHolder();

Canvas c = null;
try {
    c = holder.lockCanvas();
    if (c != null) {
        c.drawColor(Color.BLACK);
        c.drawBitmap(bg_image, 0, 0, null);
        fluid.drawParticles(c);
    }
} finally {
    if (c != null) holder.unlockCanvasAndPost(c);
}

mHandler.removeCallbacks(mDrawRunnable);
mHandler.postDelayed(mDrawRunnable, 1000/targetFramerate -(System.currentTimeMillis() - mLastTime));
}
wopkins
  • 53
  • 4

1 Answers1

2

My guess is that your animation is too complex to keep up with your frame rate. If you slow the frame rate way down, do you still have the problem? Also, if you are drawing an opaque background bitmap at each frame, you do not need to paint the screen black first--that just wastes time, and limits your maximum frame rate.

I'm guessing that the problem does not happen in preview mode because more of the phone's resources are focused on you, whereas once the wallpaper is set, more stuff is going on in the background.

George Freeman
  • 2,260
  • 1
  • 15
  • 22
  • @wopkins thanks for accepting my answer. :-) I don't know what kind of wallpaper you're making, but your use of the word "particle" makes me think you might want to look at game engines, too (AndEngine, LibGDX). Also, I think the source for the galaxy wallpaper is available here: http://android.git.kernel.org/?p=platform/packages/wallpapers/Basic.git;a=tree;f=src/com/android/wallpaper – George Freeman Apr 10 '11 at 16:36