6.8.12. Implementing the SurfaceHolder.Callback Methods

Figure 6.18 implements the surfaceChanged, surfaceCreated and surfaceDestroyed methods of interface SurfaceHolder.Callback. Method surfaceChanged has an empty body in this app because the app is always displayed in portrait orientation. This method is called when the SurfaceView’s size or orientation changes, and would typically be used to redisplay graphics based on those changes. Method surfaceCreated (lines 485–494) is called when the SurfaceView is created—e.g., when the app first loads or when it resumes from the background. We use surfaceCreated to create and start the CannonThread to begin the game loop. Method surfaceDestroyed (lines 497–515) is called when the SurfaceView is destroyed—e.g., when the app terminates. We use the method to ensure that the CannonThread terminates properly. First, line 502 calls CannonThread’s setRunning method with false as an argument to indicate that the thread should stop, then lines 504–515 wait for the thead to terminate. This ensures that no attempt is made to draw to the SurfaceView once surfaceDestroyed completes execution.


477      // called when surface changes size
478      @Override
479      public void surfaceChanged(SurfaceHolder holder, int format,
480         int width, int height)
481      {
482      }
483
484       // called when surface is first created
485      @Override
486      public void surfaceCreated(SurfaceHolder holder)
487      {
488         if (!dialogIsDisplayed)
489         {
490            cannonThread = new CannonThread(holder); // create thread
491            cannonThread.setRunning(true); // start game running     
492            cannonThread.start(); // start the game loop thread      
493         }
494      }
495
496      // called when the surface is destroyed
497      @Override
498      public void surfaceDestroyed(SurfaceHolder holder)
499      {
500         // ensure that thread terminates properly
501         boolean retry = true;
502         cannonThread.setRunning(false); // terminate cannonThread
503
504         while (retry)
505         {
506            try
507            {
508               cannonThread.join(); // wait for cannonThread to finish
509               retry = false;
510            }
511            catch (InterruptedException e)
512            {
513               Log.e(TAG, "Thread interrupted", e);
514            }
515         }
516      } // end method surfaceDestroyed
517


Fig. 6.18 | Implementing the SurfaceHolder.Callback methods.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset