Book Image

Mastering Android Game Development

By : Raul Portales
Book Image

Mastering Android Game Development

By: Raul Portales

Overview of this book

Table of Contents (18 chapters)
Mastering Android Game Development
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
API Levels for Android Versions
Index

Improving DrawThread


To trigger the draw we have been using a Timer and TimerTask scheduled so we could get 30 frames per second. While this works, it gives better performance to do it like the UpdateThread: run as many calls to onDraw as we can.

This approach works great for SurfaceView since the drawing is done on the same thread. But it may give some message overflow problems while using StandardGameView, which just calls postInvalidate. To prevent the overflow, we will ensure that the time between the calls to onDraw is never shorter than 20 milliseconds, which is enough for 50 frames per second.

The code for the new DrawThread is exactly the same as for UpdateThread, except for the part in the run method that takes care of the overflow. It looks like this:

@Override
public void run() {
  long elapsedMillis;
  long currentTimeMillis;
  long previousTimeMillis = System.currentTimeMillis();

  while (mGameIsRunning) {
    currentTimeMillis = System.currentTimeMillis();
    elapsedMillis ...