Restarting/Pausing Thread in onResume/onPause

Cyril Horad picture Cyril Horad · Aug 15, 2011 · Viewed 8.5k times · Source

I'm have a game that's uses SurfaceView implementation to display the objects. I have a thread which draws the SurfaceView time-to-time to the screen. The game is running completely. Unfortunately, it needed to have a pause function whenever the game is interrupted. Well, I know that I need to manipulate onResume and onPause.

But I can't get it right. The error points me back to surfaceCreated where I start the thread telling me that the thread has started already. I tried using the resume and suspend on the onResume and onPause respectively but nothing changed.

How can I achieve this? I have already done how the objects location would be save using File-I/O handling.

Thanks in advance.

Answer

Zappescu picture Zappescu · Aug 16, 2011

This is what I did:

    @Override
    public void surfaceCreated(SurfaceHolder arg0) {
           if (thread.getState() == Thread.State.TERMINATED){
              CreateThread(getHolder(),getContext());
           }
           thread.setRunning(true);
           thread.start();
    }
  • In CreateThread you should have the thread = new MyThread(...);
  • the setRunning (boolean mRun) use a boolean to start/stop the run function (I think I was inspired by the LunarLander);

If you want to use properly the onPause/onResume don't put the variables used by your thread inside the thread (as done in LunarLander). I suggest you to do like that:

// Variables declarations

public MyGameThread CreateThread(...){
thread = new MyGameThread(holder, context, new Handler() {
// and so on....
});
}

When you pass through the onPause/onResume, your thread will be destroyed and reneweled but if you put your variables outside it, you can continue to use them after.

If you have something important to preserve, use one of this options:

  • SharedPreferences: an xml will be created and saved locally with variables that persist even after the end of the app;
  • a SQL db if you would manage more than 5-10 variables because in this case the use of the former option would be difficult.