Surfaceview in Android is the best choice for games, and the refresh interface in surfaceview is actively refreshed: for example, the following code:
After running draw () in the run method, sleep for 100 milliseconds
Public void run () {While (misrunning) {// Add the thread security lock synchronized (msurfaceholder) Here {/** get the current canvas and lock it **/mcanvas = msurfaceholder. lockcanvas (); Draw ();/** unlock the screen after painting ends **/msurfaceholder. unlockcanvasandpost (mcanvas);} Try {thread. sleep (100);} catch (interruptedexception e) {e. printstacktrace ();}}}
This code looks very standard. In fact, the time used when the draw () method is executed is not estimated, that is, sometimes 1 s is executed or 1.1 s is executed, in this case, the problems are obvious.
Paste a piece of scientific control game-making loop code, the main thread of each loop game
The time consumed by the draw () method is calculated before and after the draw () method, and then the screen is refreshed at 30 frames to determine whether the screen is refreshed, if yes, continue the next loop. If not, use the thread. yield (); allows the main game thread to wait and calculate the current wait time until the wait time reaches 30 frames and continues refreshing the game screen in the next loop.
Thread. Yield (): And thread. Sleep (long
Millis): difference, thread. Yield (): Is to pause the currently executing thread object and execute other threads. Thread. Sleep (long
Millis): indicates the number of milliseconds specified in the parameter for pausing the current thread and then continuing to execute the thread.
/** Refresh the screen every 30 frames **/public static final int time_in_frame = 30; @ override public void run () {While (misrunning) {/** get the time before updating the game **/long starttime = system. currenttimemillis ();/** Add the thread security lock here **/synchronized (msurfaceholder) {/** get the current canvas and lock it **/mcanvas = msurfaceholder. lockcanvas (); Draw ();/** unlock the screen after painting ends **/msurfaceholder. unlockcanvasandpost (mcanvas);}/** get the end time of the update game **/long endtime = system. currenttimemillis ();/** calculates the number of milliseconds for a game update **/INT difftime = (INT) (endtime-starttime ); /** ensure that each update time is 30 frames **/while (difftime <= time_in_frame) {difftime = (INT) (system. currenttimemillis ()-starttime);/** thread waiting **/thread. yield ();}}}