Search code examples
javaandroidtimeronresumeonpause

Using onPause()/onResume() for pausing/resuming a timer of a minigame?


So here's the situation. I've been working on a minigame for android and this game has a timer that makes a countdown from 60 to 0.

http://postimg.org/image/5kcbo7t49/

When you click the pause button (II), it displays a dialog that serves as a pause, the timer should stop and of course when you click on continue it should continue.

http://postimg.org/image/j2j80i59l/

My issue is that the timer keeps working even when the Dialog pops, i thought that i could stop the timer on the onPause() method but I read that the dialogs doesnt call the onPause method because theyre not necessarily activities. So, my question is, what could i use to make my activity call the onPause() and onResume()? Should i use something different than dialogs? if so, what could i use? Or can i force the onPause/OnResume to activate in some way and is taht convenient?

Here's some code:

The code for the pause button. Just calls the pause dialog.

_Btn_Pause.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                GameManager.createDialogPause(_Activity, _Activity);
            }
        });

The code for the pause and on resume methods.

protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        _C.cancel();
        _TimeReady = 4;
        _StartGame = false;
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        setGame();
    }
public void setGame() {
    _C.scheduleAtFixedRate(_GameTimer, 1000, 1000);
}

Solution

  • Since you are passing the Activity context to the Dialog you could use it to get your Activity and call a method to stop/resume the timer.

    YourActivityName activity = (YourActivityName) _Activity;
    activity.pause_timer()  //Or call onPause() onResume()