This article describes the method of implementing a complete game loop on Android. Share it for your reference. The details are as follows:
1. :
package ; import ; import ; import ; import ; import ; public class DroidzActivity extends Activity { /** Called when the activity is first created. */ private static final String TAG = (); @Override public void onCreate(Bundle savedInstanceState) { (savedInstanceState); // requesting to turn the title OFF requestWindowFeature(Window.FEATURE_NO_TITLE); // making it full screen getWindow().setFlags(.FLAG_FULLSCREEN, .FLAG_FULLSCREEN); // set our MainGamePanel as the View setContentView(new MainGamePanel(this)); (TAG, "View added"); } @Override protected void onDestroy() { (TAG, "Destroying..."); (); } @Override protected void onStop() { (TAG, "Stopping..."); (); } }
2. :
package ; import ; import ; public class MainThread extends Thread { private static final String TAG = (); private SurfaceHolder surfaceHolder; private MainGamePanel gamePanel; private boolean running; public void setRunning(boolean running) { = running; } public MainThread(SurfaceHolder surfaceHolder, MainGamePanel gamePanel) { super(); = surfaceHolder; = gamePanel; } @Override public void run() { long tickCount = 0L; (TAG, "Starting game loop"); while (running) { tickCount++; // update game state // render state to the screen } (TAG, "Game loop executed " + tickCount + " times"); } }
3. :
package ; import ; import ; import ; import ; import ; public class MainGamePanel extends SurfaceView implements { private MainThread thread; public MainGamePanel(Context context) { super(context); getHolder().addCallback(this); // create the game loop thread thread = new MainThread(); setFocusable(true); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceCreated(SurfaceHolder holder) { (true); (); } @Override public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; while (retry) { try { (); retry = false; } catch (InterruptedException e) { // try again shutting down the thread } } } @Override public boolean onTouchEvent(MotionEvent event) { return (event); } @Override protected void onDraw(Canvas canvas) { } }
I hope this article will be helpful to everyone's Android programming design.