Renoki: Making An Android Game (part 6)

The Home Button

I decided my next step was to implement player state information (lives, items acquired, gold, points, etc). I realized that by adding these, I would also have to handle saving state between closing and opening of my app. This is where I ran into some annoying issues.

The lifetime of your Android app can be modeled by this:

What’s annoying is that pressing “Back” and pressing “Home” are completely different things. Pressing “Back” will cause the kernel to destroy your app, effectively closing it and freeing all the resources your app has allocated. Originally, I had planned that when a user resumes playing my app, they would always begin at the start of whatever level they were last at. This would save me the trouble of saving tons of game state variables, like what monsters are in the game board at the time they last exited. Instead, I just need to save the level. If the user exits my app with “Back”, then all of this works as planned.

The problem occurs when the user exits my app by pressing “Home”. The Home key will immediately return to the homescreen, but will NOT destroy your app. It will call the onStop() method and then your app will continue to run in the background. Interestingly enough, this is the exact same behavior that will occur if you receive a phone call while playing your app, or any other activity interrupts your app. This is where I have two choices, which are implemented very nicely by Plants vs Zombies and Angry Birds.

If Plants vs Zombies gets interrupted, either by Home Key or phone call, when you restart it you will see a loading bar. Once loading is complete, it will place you in the exact state you were in except the game is paused. This implies that they are manually freeing memory or something of the sort, and when you resume they have to spend the time to reload it. On the other hand, when Angry Birds gets interrupted, restarting it is instant. There is zero loading time and you immediately return to the exact moment but paused. This implies that the Angry Birds pause screen is still running at full capacity in the background of your phone.

So for my game, I’m probably going to take the Angry Birds approach and just have my game continue to run in the pause screen whenever users press Home. The game loop will continue to run, just each iteration will do nothing. All the graphics and music will remain in memory and resuming the game will be pretty much instant. Luckily, I can still use my original plan of starting the game at the beginning of the level when the user exits correctly with the “back” button. Since everything is always running in the background, I will not need to save any player state when the user exits with “Home”.

Share Your Thoughts

Leave a Reply