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???
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It only takes a minute to sign up.Sign up to join this community
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:
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
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.
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.