views:

1187

answers:

2

I'm currently getting to grips with Android, playing around with the Lunar Lander sample.

I've found that if you navigate away from the app (eg, hit the call button) it will destroy the underlying surface (calling surfaceDestroyed).

Navigating back (which will trigger onWindowVisibilityChanged) the app will crash, as it will try to draw to the surface without recreating it.

Is there some code I can put in onWindowVisibilityChanged (or anywhere else) that will regenerate the SurfaceView's underlying surface and resume execution nicely?

It feels like this should be a simple function call but I can't find anything in the API docs.

Thanks!

A: 

Mis-diagnosis! The app re-creates the surface automatically, but there's a call in there that tries to draw to it before it's created.

Fixing the problem:

boolean mSurfaceExists;
...
public void surfaceDestroyed(SurfaceHolder holder) {
    mSurfaceExists = false;
    ...
}

public void surfaceCreated(SurfaceHolder holder) {
    mSurfaceExists = true;
    ...
}

protected void onWindowVisibilityChanged(int visibility) {
    // only call base if there's a surface
    if(mSurfaceExists)
     super.onWindowVisibilityChanged(visibility);
}

Now it's all swell. (as far as I'm aware, anyway - Java/Android experts feel free to comment if this is bad practise!)

frezned
I have tried this and it doesn't draw the lunar lander game properly. All you get is the text not the space ship or background.