Surface Holder and Locking

In order to render to a SurfaceView from a different thread than the UI thread, we need to acquire an instance of the SurfaceHolder class, like this:

SurfaceHolder holder = surfaceView.getHolder();

The SurfaceHolder is a wrapper around the Surface, and does some bookkeeping for us. It provides us with two methods:

Canvas SurfaceHolder.lockCanvas(); SurfaceHolder.unlockAndPost(Canvas canvas);

The first method locks the Surface for rendering and returns a nice Canvas instance we can use. The second method unlocks the Surface again and makes sure that what we've drawn via the Canvas gets displayed on the screen. We will use these two methods in our rendering thread to acquire the Canvas, render with it, and finally make the image we just rendered visible on the screen. The Canvas we have to pass to the SurfaceHolder.unlockAndPost() method must be the one we received from the SurfaceHolder.lockCanvas() method.

The Surface is not immediately created when the SurfaceView is instantiated. Instead it is created asynchronously. The surface will be destroyed each time the activity is paused and recreated when the activity is resumed again.

0 0

Post a comment