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: