views:

461

answers:

3

Hey,

Just come to polishing my application and making it resume after the user has left. When the application restores I get an IllegalThreadStateException, which is quite annoying. This problem is present in the example google gives of Lunar Lander. Has anyone found a way to restore working when using surfaceView?

Cheers

A: 

I believe this arises from a disparity in how the Surface and the Activity are handled. When you leave the LunarLander application the surface is destroyed (invoking surfaceDestroyed) but the Activity is only paused (invoking onPause). When the Activity is resumed the surface is created (invoking surfaceCreated) and it attempts to start the drawing thread again.

This means that creating the Thread happens with the Activity's lifecycle and destroying the thread happens with the SurfaceView's lifecycle, which do not always correspond, thus the IllegalThreadStateException. The solution would be to tie the thread to one lifecycle or the other, not both.

I think this thread proposes a possible solution, though I don't know if it works.

Soonil
I have tried the link and it does not work. Do I need to instantiate the thread in surfaceCreated? I have tried this but the program crashes.
+1  A: 

In my own test, I create the drawing thread in the surfaceCreated() method, and this solves the issue completely. This is my method implementation:

@Override
public void surfaceCreated(SurfaceHolder arg0) {
    _thread = new DrawThread(getHolder());
    _thread.setRunning(true);
    _thread.start();
}
Ruben