views:

221

answers:

2

I have a surfaceView setup and running, but when i resume it i get an error that the thread has already been started. Whats the proper way to handle when the app goes to the background and then back to the foreground? Ive tinkered around and managed to get the app to come back without crashing...but the surfaceView doesnt draw anthing anymore. My code:

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
           Log.e("sys","surfaceCreated was called.");
           if(systemState==BACKGROUND){
                  thread.setRunning(true);

           }
           else {
        thread.setRunning(true);
               thread.start();
               Log.e("sys","started thread");
               systemState=READY;
           }



    }
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
           Log.e("sys","surfaceDestroyed was called.");
           thread.setRunning(false);
           systemState=BACKGROUND;
    }
A: 

You should use the Activities onPause() and onResume() methods.

First, in surfaceCreated(), start the thread. Also, in onResume(), make sure the thread isn't already started (keep a variable inside the thread or something). Then if it is not running, set it as running again. in onPause(), pause the thread. In surfaceDestroyed, pause the thread again.

Moncader
I have it properly set to use setRunning in the appropriate places, but despite having thread.setRunning(true) in my onResume my surfaceView is blank when its back in the forefront. The thread is still there, it doesnt crash the app when i go to the home screen, and if i do try another thread.start() i get the error saying that the threads been started. Any ideas?
Evan Kimia
You can only ever start a thread once. I don't know what your setRunning method does on the inside, but the only way to properly stop a thread on Android is to let it return from its run() method. From that point onwards, you 'must' create a new thread object. You can not use that thread ever again. If you want to 'pause' the thread, you have to use wait() and notifyAll(). Google around for example and proper understanding on that.
Moncader
+1  A: 

The easy solution is to simply kill and restart the thread. Create methods resume() - creates thread object and states it - and pause() - kills thread (see Lunarlander examåøe) - in your SurfaceView class and call these from surfaceCreated and surfaceDestroyed to start and stop the thread.

Now in the Activity that runs the SurfaceView, you will also need to call the resume() and pause() methods in the SurfaceView from the Activity's onResume() and onPause(). It's not an elegant solution, but it will work.

Michael A.
I love Ur idea, I have been working around to find something easy. Because "surfaceDestroyed " is not called everytime but "onPause" is. Just like pressing "power" button then return. So I think your choice is a really good one.
Steven Shih