This app performs its animations manually by updating the game elements from a separate thread of execuion. To do this, we use a subclass of Thread
with a run
method that directs our custom CannonView
to update the positions of the game’s elements, then draws them. The run
method drives the frame-by-frame animations—this is known as the game loop.
Normally, all updates to an app’s user interface must be performed in the GUI thread of execution. In Android, it’s important to minimize the amount of work you do in the GUI thread to ensure that the GUI remains responsive and does not display ANR (Application Not Responding) dialogs. However, games often require complex logic that should be performed in separate threads of execution and those threads often need to draw to the screen. For such cases, Android provides class SurfaceView—a subclass of View
to which a thread can draw, then indicate that the results should be displayed in the GUI thread. You manipulate a SurfaceView
via an object of class SurfaceHolder, which enables you to obtain a Canvas
on which you can draw graphics. Class SurfaceHolder
also provides methods that give a thread exclusive access to the Canvas
for drawing—only one thread at a time can draw to a SurfaceView
. Each SurfaceView
subclass should implement the interface SurfaceHolder.Callback, which contains methods that are called when the SurfaceView
is created, changed (e.g., its size or orientation changes) or destroyed.