Dealing With Android Activity States

It is important to understand how Android activities work in the context of persisting game data across different states. For complex apps one might require more than one activity, and retaining state as well as catering for abrupt pauses or exits can be a bit confusing. It's a very important design decision on how your app might handle these cases in the context of data persistence and usability.

An activity has many states as displayed in the state diagram below, but almost all the cases can be catered for just by using onPause, onStart and onResume. onPause will always be called when pausing/quitting an application pressing the home button or due to taking a phone call. onStart will only be called when a new Activity instance is created. 


Warlock's Bounty uses xml serialization for presistence; every time onPause() is called in the Activity, a write to a temporary xml is executed so that when the app is opened  subsequently, it will check via onStart() if this xml exists, if yes then it resumes it's state and deletes the temporary xml. As Warlock's Bounty is turn based, there's no need to implement onResume() because there's no need to start/pause any entities in the game itself. 

public void onPause(){ 

public void onStart(){
File file = new File(PersistenceManager.saveTempGameFilename);
//we load it then, only if it exists
if (file.exists()) {
//load data
//delete data

Don't forget to think about how you want your application to behave when the user presses the back button? Do you want it to save its state and go to start menu where the user will be presented with say a continue button, or do you want it to just quit and not save the state? You will need to handle this back key event well by implementing onBackPressed() in your Activity. One caveat is that you will need to have Android ver 2.1 or above, otherwise  you need to do additonal coding.