Search code examples
androidmultithreadingviewvsync

How does animation at 60Hz works?


I'm using a Thread to make a scrolling under Android. The thread run method is classic. I took it on Internet My view is a SurfaceView.

public void run() {
    Canvas canvas = null;
    while (_run) {
        canvas = _surfaceHolder.lockCanvas();
        if (canvas != null) {
            _surface.doDraw(canvas);
            _surfaceHolder.unlockCanvasAndPost(canvas);
        }
    }
}

What I do not understand is: Why the doDraw (that will draw on screen) is called exactly 60 times per second ? And why there is no synchro problem ?

I do not know how LCD works but on a screen, if you make a scrolling without waiting for the screen synchro, it is possible that the top of the screen display the previous image while the bottom display the correct image. I do not have the problem on Android.

Is it the SurfaceView that handle a kind of double buffering ? And if it is the case, when the flip is done ?

I do not find any information about that on Internet!

Thank's Etienne


Solution

  • It is indeed double buffered, the flip is done in SurfaceHolder.unlockCanvasAndPost().

    Check this out: http://developer.android.com/reference/android/view/SurfaceHolder.html#unlockCanvasAndPost(android.graphics.Canvas)

    [Edit] Sorry, forgot your first question.

    Android always have vsync enabled, and therefore either lockCanvas() or unlockCanvasAndPost() will block the remaining time to sync it. I don't know im my head if it is lockCanvas() or unlockCanvasAndPost() that blocks, but it should be easy enough to check if you'd need it.