Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MyGame extends SurfaceView implements SurfaceHolder.Callback {
- private GameThread thread;
- private Paint paint;
- public MyGame(Context context) {
- super(context);
- // Initialize the game thread and paint object
- thread = new GameThread(getHolder(), this);
- paint = new Paint();
- // Add this class as a surface holder callback
- getHolder().addCallback(this);
- }
- @Override
- public void surfaceCreated(SurfaceHolder holder) {
- // Start the game thread when the surface is created
- thread.setRunning(true);
- thread.start();
- }
- @Override
- public void surfaceDestroyed(SurfaceHolder holder) {
- // Stop the game thread when the surface is destroyed
- boolean retry = true;
- while (retry) {
- try {
- thread.setRunning(false);
- thread.join();
- retry = false;
- } catch (InterruptedException e) {
- // Do nothing
- }
- }
- }
- @Override
- public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
- // Do nothing
- }
- @Override
- public void draw(Canvas canvas) {
- super.draw(canvas);
- // Draw a circle onto the canvas
- canvas.drawCircle(getWidth() / 2f, getHeight() / 2f, 100f, paint);
- }
- private class GameThread extends Thread {
- private SurfaceHolder holder;
- private MyGame game;
- private boolean running;
- public GameThread(SurfaceHolder holder, MyGame game) {
- this.holder = holder;
- this.game = game;
- running = false;
- }
- public void setRunning(boolean running) {
- this.running = running;
- }
- @Override
- public void run() {
- while (running) {
- // Update the game logic
- // ...
- // Draw the game onto the canvas
- Canvas canvas = null;
- try {
- canvas = holder.lockCanvas();
- synchronized (holder) {
- game.draw(canvas);
- }
- } finally {
- if (canvas != null) {
- holder.unlockCanvasAndPost(canvas);
- }
- }
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment