Android game thread lifecycle implementation

So, I'm working on a new basic 2d game for Android and setting up my usual implementation of a game stream that works with SurfaceView. While I was typing, I realized that although this seems to work, I would really like to know if there is a better way to achieve the same results. Here is the basic information about what I'm doing right now (I apologize for the verbosity, I try to squeeze as much as possible):

GameActivity Class

@Override
public void onCreate(final Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.game);

    this.mGameView = (GameView)this.findViewById(R.id.gameview);
}

XML layout

<?xml version="1.0" encoding="utf-8" ?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
 <com.package.name.GameView
    android:id="@+id/gameview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:focusable="true"
        android:focusableInTouchMode="true" />
</merge>

Gameview

@Override
public void surfaceCreated(final SurfaceHolder holder) { }

@Override
public void surfaceChanged(final SurfaceHolder holder, final int format, 
                            final int width, final int height)
{
    this.mGameThread = new GameThread(this.getContext(), holder, 
                                        width, height);

    this.mGameThread.start(); // starts the game
}

@Override
public void surfaceDestroyed(final SurfaceHolder holder)
{
    // flips volatile flag stopping execution
    // then calls .join()
    this.mGameThread.release(); 
}

GameThread Class

@Override
public void run()
{
    // load game state
    while (this.mRunFlag) // volatile loop flag
    {
        // game loop
    }
    // save game state
}

As you can see, I mainly rely on SurfaceHolder callbacks to control the game. This works well with orientation changes, etc., but without asking, I may never know if this can be achieved better, which I would like to know if there is. So that’s why I ask! Any thoughts?

(, , , Activity , ...)

+3
1

, , onSurfaceChanged , ( , - , VRAM , , ).

, , , , , . . . onPause onSurfaceDestroyed ( , , ). onResume onSurfaceChanged , . , ( . ) , . , , .

+1

Source: https://habr.com/ru/post/1750931/


All Articles