views:

215

answers:

1

I am making an Android game with an Activity called Game, a SurfaceView called GameView and a Thread called GameThread. The Game's onCreate(), I make a new GameView, which makes a new GameThread, where all the game logic and canvas drawing is carried out.

However, I'm having some lifecycle difficulties. When I press back and restart it, it works fine, but when I press home and restart it, all I see is a blank screen. Here are the GameView's onSurfaceCreated() and onSurfaceDestroyed():

@Override
public void surfaceCreated(SurfaceHolder holder) {
    mThread.mRunning = true;
    mThread.mWidth = getWidth();
    if(mThread.mWidth > 550) mThread.mWidth = 550;
    mThread.mHeight = getHeight();
    try {
        mThread.start();
    } catch(IllegalThreadStateException e) {
    }

}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    // Wait for the secondary thread to end before finishing
    boolean retry = true;
    mThread.mRunning = false;
    while (retry) {
        try {
            mThread.join();
            retry = false;

        } catch (InterruptedException e) {
        }
    }       
}
A: 

In my experience, the Back Button finish the Activity, so when you restart it, the onCreate method is called again.

The Home Button instead don't finish the Activity, when you press the Home Button the onPause method of the activity is called, and when you restart it, the method called is onResume.

I guess you have some code in the onCreate that is the responsible for creating the SurfaceView. Try to add this code to the onResume method (overriding it)...

YaW
Thanks. Creating the SurfaceView in onResume makes it work.
sirconnorstack
Was your SurfaceView null when the Activity was "restarted"? How about your thread, did you have to start it again? I'm not sure how creating the SurfaceView explicitly would help, maybe I don't get it.
Flynn81