How to update a SurfaceView between fixed intervals in Android?
<p>I'm writing a little program based on the LunarLander example project. What I want to achieve is to update my <code>SurfaceView</code> (reposition some <code>Drawable</code>s mainly) between fixed intervals like this one:</p>

<pre><code>private static final int UPDATE_INTERVAL = 1000 / 20; // 20 FPS
</code></pre>

<p>I'm running a <code>Thread</code> which is doing this in its <code>run()</code> method:</p>

<pre><code>@Override
    public void run() {
        while (isRunning) {
            Canvas c = null;
            try {
                c = view.getSurfaceHolder().lockCanvas(null);
                synchronized (view.getSurfaceHolder()) {
                    if (GameState.RUNNING.equals(state)) {
                        long now = System.currentTimeMillis();
                        if (now - lastUpdate &gt; UPDATE_INTERVAL) {
                            lastUpdate = now;
                            updater.updatePieces();
                        }
                        doDraw(c);
                    }
                }
            } finally {
                if (c != null) {
                    view.getSurfaceHolder().unlockCanvasAndPost(c);
                }
            }
        }
    }
</code></pre>

<p>My problem is that it is possible that this <code>Thread</code> is busy waiting for the <code>(now - lastUpdate &gt; UPDATE_INTERVAL)</code> condition to be <code>true</code>. But there is an other case if redrawing takes more than 1000 / 20 seconds. This means that the animation is not always seamless. I tried it out in my emulator and it is usually OK but sometimes my <code>Drawable</code> is slowing down and after that it speeds up for approximately a half second. Is this just the emulator or something else?</p>

<p>I won't bother you with the details, <code>updatePieces()</code> just moves a little circle from top to bottom. I'm not creating any new objects. I somehow get the feeling that this piece of code is not right. Is this a good practice for animating <code>Drawable</code>s or I'm missing something obvious? I'm kind of new in this topic.</p>

<p>I propagate touch and key events from the UI thread to this one so I don't really want to call <code>sleep()</code> in this <code>Thread</code> because it may cause the UI thread to become unresponsive.</p>
