27 March 2011

[Technote] Saving states from Android Activities

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):
  • Using Bundle to save primitive typed (check for Bundle API), temporary data.
  • Using SharedPreferences to save primitive typed, persistent data.
  • Using onRetainNonConfigurationInstance to save temporary object instances.
I personally find the last bullet very useful because the data we want to save cannot always be primitive typed! For more details about the differences and usages of the three approaches, check out here.

To retrieve data you saved, onCreate is a good place for your activity to reload states. According to my experience, onCreate is probably and mostly what you really want, not onResume or onStart otherwise.

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 onActivityResult method. Then, in the callee, remember to call setResult to set the result to be returned, before the activity is finished.

No comments: