title: Preventing "flickering" when calling Drawable.draw()
body: <p>I have a little experimentation app (essentially a <em>very</em> cut-down version of the <a href="http://developer.android.com/resources/samples/LunarLander/index.html" rel="nofollow">LunarLander</a> demo in the Android SDK), with a single <code>SurfaceView</code>.  I have a <code>Drawable</code> "sprite" which I periodically draw into the <code>SurfaceView</code>'s <code>Canvas</code> object in different locations, without attempting to erase the previous image.  Thus:</p>
  
  <pre><code>private class MyThread extends Thread {
      SurfaceHolder holder;  // Initialised in ctor (acquired via getHolder())
      Drawable      sprite;  // Initialised in ctor
      Rect          bounds;  // Initialised in ctor
  
      ...
  
      @Override
      public void run() {
          while (true) {
              Canvas c = holder.lockCanvas();
              synchronized (bounds) {
                  sprite.setBounds(bounds);
              }
              sprite.draw(c);
              holder.unlockCanvasAndPost(c);
          }
      }
  
      /**
       * Periodically called from activity thread
       */
      public void updatePos(int dx, int dy) {
          synchronized (bounds) {
              bounds.offset(dx, dy);
          }
      }
  }
  </code></pre>
  
  <p>Running in the emulator, what I'm seeing is that after a few updates have occurred, several old "copies" of the image begin to flicker, i.e. appearing and disappearing.  I initially assumed that perhaps I was misunderstanding the semantics of a <code>Canvas</code>, and that it somehow maintains "layers", and that I was thrashing it to death.  However, I then discovered that I only get this effect if I try to update faster than roughly every 200 ms.  So my next best theory is that this is perhaps an artifact of the emulator not being able to keep up, and tearing the display.  (I don't have a physical device to test on, yet.)</p>
  
  <p>Is either of these theories correct?</p>
  
  <p><em>Note: I don't actually want to do this in practice (i.e. draw hundreds of overlaid copies of the same thing).  However, I would like to understand why this is happening.</em></p>
  
  <p><strong>Environment:</strong></p>
  
  <ul>
  <li>Eclipse 3.6.1 (Helios) on Windows 7</li>
  <li>JDK 6</li>
  <li>Android SDK Tools r9</li>
  <li>App is targetting Android 2.3.1</li>
  </ul>
  
  <p><strong>Tangential question:</strong></p>
  
  <p>My <code>run()</code> method is essentially a stripped-down version of how the LunarLander example works (with all the excess logic removed).  I don't quite understand why this isn't going to saturate the CPU, as there seems to be nothing to prevent it running at full pelt.  Can anyone clarify this?</p>