I'm writing a small turn-based game using libgdx. How to make a timer on the player turn to make it work even when the game loses focus??

Or maybe there are some other ways to do it???

  • \$\begingroup\$ @Tyyppi_77 when the game loses focus, the timer expires, the game nothing happens. I would like to have a player who does not have time to make a move - lost \$\endgroup\$ – kovac777 Aug 11 '16 at 12:17
  • \$\begingroup\$ There is something called background service on Android. This is more android/platform specific question, not pure game development one. \$\endgroup\$ – Mars Aug 11 '16 at 12:20
  • \$\begingroup\$ @Mars I wanted to try it now. Maybe there are some other ways to do it??? \$\endgroup\$ – kovac777 Aug 11 '16 at 12:24

When your Android app is in the background, you have no guarantee that the OS will not close it so that another app can have its resources.

Here are two options:

  1. Android will notify your app of some events in it's lifecycle so you will know that your app is going into the background (you'll probably want to use onPause and onResume). Instead of creating a timer when a player's turn starts, you could store the timestamp when the player's turn starts. When the Android lifecycle notifies you that your app is going into the background, save this timestamp to a file in case your app is closed. Once your app is resumed, check the current time against the saved timestamp and simulate the game steps until it is caught up.

  2. Create an Android service. Android services are just like windows services, except, in my experience, they are a bit trickier to write. The service would be the master timekeeper and you app would have to communicate with it. Once started, an Android service will keep running, meaning that once you are not using the service, you are responsible to shut it down.

  • \$\begingroup\$ I selected second option, it is work very perfectly!! \$\endgroup\$ – kovac777 Aug 11 '16 at 17:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.