本文实例讲述了Android基本游戏循环。分享给大家供大家参考。具体如下:
// desired fpsprivate final static intMAX_FPS = 50;// maximum number of frames to be skippedprivate final static intMAX_FRAME_SKIPS = 5;// the frame periodprivate final static intFRAME_PERIOD = 1000 / MAX_FPS; @Overridepublic void run() {Canvas canvas;Log.d(TAG, "Starting game loop");long beginTime; // the time when the cycle begunlong timeDiff; // the time it took for the cycle to executeint 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 surfacetry {canvas = this.surfaceHolder.lockCanvas();synchronized (surfaceHolder) {beginTime = System.currentTimeMillis();framesSkipped = 0; // resetting the frames skipped// update game statethis.gamePanel.update();// render state to the screen// draws the canvas on the panelthis.gamePanel.render(canvas);// calculate how long did the cycle taketimeDiff = System.currentTimeMillis() - beginTime;// calculate sleep timesleepTime = (int)(FRAME_PERIOD - timeDiff);if (sleepTime > 0) {// if sleepTime > 0 we"re OKtry {// send the thread to sleep for a short period// very useful for battery savingThread.sleep(sleepTime);} catch (InterruptedException e) {}}while (sleepTime < 0 && framesSkipped < MAX_FRAME_SKIPS) {// we need to catch up// update without renderingthis.gamePanel.update();// add frame period to check if in next framesleepTime += FRAME_PERIOD;framesSkipped++;}}} finally {// in case of an exception the surface is not left in// an inconsistent stateif (canvas != null) {surfaceHolder.unlockCanvasAndPost(canvas);}}// end finally}}
希望本文所述对大家的Android程序设计有所帮助。