[Android] Activity LifeCycles and that weird savedInstanceState
You'll notice that when you first create an Activity you will have an onCreate() method where you pass a savedInstanceState. What is the savedInstanceState all about???
An Activity has a lifecycle of different states.
onCreate --> will be called when the activity is created for the first time
onPause --> will be called just before the current activity is about to be paused, to switch to either another activity or a different app. For example, when you get a phone call in the middle of your app activity, onPause() will be called.
onResume --> will be called after onPause() was called and just before the activity is resumed (i.e., when you return from the phone call)
onDestroy --> this is an important one and needs to be handled appropriately.onDestroy is called just before your app session is about to be entirely destroyed by the system, meaning all app session data will be deleted (an exception to this is widget data, that will be retained through a destroy). Typically, when the system's memory is getting tight, the system may go through all the apps running in the background and destroy your app's session. Again, just before the system is about to destroy your app, it will send a message to your app to call two methods:onSavedInstanceState() and onDestroy(). What a nice warning! So here's your chance to save any 'state' related data. For example, you may want to save instance variables in your activity, like user selections or text entries (note, for more persistant data like user attributes, you'll want to use a SQL database to store the data across sessions).
*** Tricky *** Screen rotations and pulling out the keyboard on some devices will also cause an activity to be destroyed by default. So you also need to handle these cases.
So, how do you save this stuff?
We will use the onSavedInstanceState method and create something called a Bundle, which is basically a set of name-value pairs. This bundle will then be passed to onCreate to be resurrected, when the app is restored. Here's an example.