Search code examples
androidmultithreadingsurfaceviewonresumeonpause

Restarting/Pausing Thread in onResume/onPause


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.


Solution

  • Without knowing the ins and outs of your code.

    To "Pause" a thread you can implement functionality like so:

    while(! this.isInterrupted())
        if(!paused)
        {
            ... Do something ...
        } else { try { Thread.sleep(100) } catch (InteruptedException ie) {} }
    

    This is depending if Do something is invalidating your surface view or otherwise controlling progression in your app. An accessor to paused should allow you to pause and resume your thread without getting caught up in any other bit of architecture.