This example describes the Android basic game cycle. Share to everyone for your reference. as follows:
Desired FPS private final static int max_fps = 50;
Maximum number of frames to be skipped private final static int max_frame_skips = 5;
The frame period private final static int frame_period = 1000/max_fps;
@Override public void Run () {Canvas Canvas;
LOG.D (TAG, "Starting game loop"); Long BeginTime; The time the cycle begun long Timediff; The time it is took for the cycle to execute int sleeptime; Ms to-sleep (<0 if we ' re behind) int framesskipped;
Number of frames being skipped sleeptime = 0;
while (running) {canvas = null; Try locking the canvas for exclusive pixel editing//In the surface try {canvas = This.surfaceHolder.lo
Ckcanvas ();
Synchronized (surfaceholder) {begintime = System.currenttimemillis (); framesskipped = 0;
Resetting the frames skipped//update game State this.gamePanel.update (); Render state to the screen//draws the CANVAs on the panel this.gamePanel.render (canvas);
Calculate how long did the cycle take Timediff = System.currenttimemillis ()-begintime;
Calculate sleep Time Sleeptime = (int) (FRAME_PERIOD-TIMEDIFF); if (Sleeptime > 0) {//If Sleeptime > 0 we ' re OK try {//Send the thread to sleep
For a short period//very useful for battery saving thread.sleep (sleeptime); catch (Interruptedexception e) {}} while (Sleeptime < 0 && framesskipped < Max_frame_skip
S) {//We need to catch up//update without rendering this.gamePanel.update ();
Add frame period to check if in next frame sleeptime + = Frame_period;
framesskipped++;
finally {//In case of ' an ' exception the ' surface is ' not ' left '//a inconsistent state
if (canvas!= null) { Surfaceholder.unlockcanvasandpost (canvas);
}}//End finally}}
I hope this article will help you with your Android program.