Android 2D game: who should be responsible for calling the canvas to draw?

197 Views Asked by At

In online tutorials or in the Android SDK samples of 2D games, there is usually a drawing function inside the game thread's run() method, which is responsible for drawing on the canvas. For instance, in the classical Lunar Lander code, we have the following code in class LunarThread:

@Override
public void run() {
    while (mRun) {
        Canvas c = null;
        try {
            c = mSurfaceHolder.lockCanvas(null);
            synchronized (mSurfaceHolder) {
                if (mMode == STATE_RUNNING) updatePhysics();
                doDraw(c);
            }
        } finally {
            // ...
        }
    }
}

private void doDraw(Canvas canvas) {
    canvas.drawBitmap(mBackgroundImage, 0, 0, null);
    // ...
}

The Android development guide, however, state very clearly that:

Do not access the Android UI toolkit from outside the UI thread.

I have two questions.

  1. I am puzzled by the meaning of 'Android UI toolkit'. Since the canvas is locked by the SurfaceHolder, and the SurfaceHolder is holding a surface that can accept user inputs (such as touch events), is the canvas considered an 'Android UI toolkit'?
  2. Are those tutorials or code samples violating the above rule? If so, why is such violation acceptable? If not, why not?
0

There are 0 best solutions below