0

I have a countdown timer in my game and I have to cancel it once the home button is pressed. I tried with this:

@Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();
        timer.cancel();
    }

But this does not work for me, cause I have some popup activities and some other stuff because of which I lose the focus of my main activity and that makes the timer to stop, and that's not good for me. Is there a way to stop my timer ONLY if the home button is pressed?

marjanbaz
  • 1,052
  • 3
  • 18
  • 35

3 Answers3

1

try this

@Override
public void onStop() {
     super.onStop();
     timer.cancel();
}
Kien Vuong
  • 28
  • 4
  • this will work if you don't mind how long the timer is going to run before stopping it. You cannot be sure when `onStop()` is going to be called, so your timer might "run out" and trigger some behaviour, even though your game is now in the background. – Richard Le Mesurier Aug 28 '14 at 15:43
1

This is a common type of question, with no trivial, built-in solution. But easy enough to write your own.


The basic solution relies on monitoring the onPause() and onResume() events of all your activities. This would normally be done by using a base Activity class that implements the below behaviour, and all your activities extend it.

I normally use my Application class to handle the logic of knowing when it is no longer in the foreground. So in the application class, I have methods that get called every time my activity pauses, or resumes.

when paused:

  • I start a short timer, say 300 milliseconds long

when resumed:

  • I stop that timer, if it is running

So:

  • if you launch your activity B, your Application class will get a pause signal, followed right away by a resume signal. Your timer will not expire.
  • if your application is sent to the background, you will get a pause signal, and no resume signal. Your timer WILL expire.

When the timer expires, you know that your application is in the background, and you take action. In your case, that means cancelling the game timer. Other people will log out of a server. In my case, I turn NIGHT MODE off.


You can base the code on my answer to a similar question, which shows how each activity would alert the application of its status:

In that question you can see a boolean flag is being set. In your case, you would start or stop the timer.

For more details, check out these related links:

Community
  • 1
  • 1
Richard Le Mesurier
  • 29,432
  • 22
  • 140
  • 255
0

Maybe you should stop your timer when the activity's onPause or onStop method is called.