When you start to develop applications on Android devices, managing Activity states definitely is the first major thing to master in order to create reliable, robust Android apps. Here I will simply go through what I have found during developing Android apps myself:
First, you have to think carefully what states are necessary to be retained when Android Activity is destroyed. Usually, the less states you save, the better (because that reduces your Activity start-up time as well as destroying time). For instance, you might not need to save the 'look' of View, because it can always be redrawn/recomputed every time when an Activity comes to live; instead, saving some states necessary for Android to recompute that look, i.e., the current position of the cursor on screen.
Second, you can then think about HOW to save states after determining what to save. Generally, there are three ways to do it (not including saving data on Android internal filesystem or SD card):
Bundleto save primitive typed (check for
BundleAPI), temporary data.
SharedPreferencesto save primitive typed, persistent data.
onRetainNonConfigurationInstanceto save temporary object instances.
To retrieve data you saved,
onCreateis a good place for your activity to reload states. According to my experience,
onCreateis probably and mostly what you really want, not
A side note for the above: the easiest and best way to test if your management of Activity's life cycle is correct, is to change the orientation of the screen. It should not crash and the behavior should be the same as before orientation.
Last, sometimes what we really want is to have some simple communication mechanism between activities (i.e., the calling activity and the callee activity) instead of saving states, how to achieve that? In the caller activity, call the callee with
startActivityForResult,and also implement the
onActivityResultmethod. Then, in the callee, remember to call
setResultto set the result to be returned, before the activity is finished.