Android - active rendering in game loop?

1k views Asked by At


What is the best way to render in game loop on android?
When I'm rendering in java I know how to do this. I create buffer strategy, than graphics, I draw, than dispose and than flip buffer. Is there Andorid equivalent of that?

I looked into view, but it doesn't work correctly when I try draw a lot. I looked into SurfaceView than, but I can't understand how I can refresh drawing on it. invalidate breaks the loop, postInvalidate doesn't work. I lock canvas and draw on it, and than unlock and post in "create" method from surface view (locking canvas in loop doesn't work, only white screen in app appears). So I don't get it.
What's the most efficient way to render heavily in Android?

1

There are 1 answers

2
MadEqua On BEST ANSWER

The common approach to render within a SurfaceView is through its SurfaceHolder.

Usually you'll get a Canvas through the holder and draw on it:

 SurfaceHolder surfaceHolder = surfaceView.getHolder();
 Canvas canvas = surfaceHolder.getSurface().lockCanvas();

 //draw in the canvas
 canvas.drawPoint(...);

 surfaceHolder.unlockCanvasAndPost(canvas);

The correct approach is to loop all the code between the lockCanvas() and unlockCanvasAndPost() (inclusive) in a separate thread (the render thread) and control the framerate with a Thread.sleep() inside the loop.

EDIT:

There are many ways to control the FPS of the render thread, this is a basic one, just set the wanted FPS on a constant:

public class RenderThread extends Thread {
  private boolean running;
  private final static int MAX_FPS = 30;    
  private final static int FRAME_PERIOD = 1000 / MAX_FPS;   

  @Override
  public void run() {
    long beginTime;
    long timeDiff;
    int sleepTime;

    sleepTime = 0;

    while (running) {
        beginTime = System.currentTimeMillis();

        //RENDER

        // How long did the render take
        timeDiff = System.currentTimeMillis() - beginTime;
        // calculate sleep time
        sleepTime = (int)(FRAME_PERIOD - timeDiff);

        if (sleepTime > 0) {
            try {
                Thread.sleep(sleepTime);    
            } catch (InterruptedException e) {}
        }
     }
   }
}

There are lots of references if you search for game loops.