Saturday, November 23, 2013

Android Activity Lifecycle Summary

Every instance of Activity has a lifecycle. During this lifecycle, an activity transitions between three possible states: running, paused, and stopped. For each transition, there is an method that notifies the activity of the change in its state. We take advantage of these methods to do some work at transitions.
Note: you never call any of the Activity lifecycle methods yourself. We override them in activity subclasses, and Android calls them at the appropriate time.
   To see when android calls these methods, we can override methods with d(String tag, String msg) method which is in android.util.Log.

1. onCreate(Bundle): The OS calls this method after the activity instance is created but before it is put on screen.
  • inflating widgets and putting them on screen by SetContentView(int) method.
  • getting references to inflated widgets.
  • setting listeners on widgets to handle user interaction.
  • connecting to external model data.
  One of the case that we want to override onCreate(Bundle) is to get saved data after rotation. For example: 
  onCreate() {
   ...
   if (savedInstancesState != null) {
      variable = savedInstanceState.getInt(KEY, value);
   }
  }

Saving data is done by overriding OnSaveInstanceState(Bundle) method and we need to have a key-value pair which will be saved in the bundle. onSaveInstanceState method is normally called by the system before onPause(), onStop(), and onDestroy(). The data is saved to the Bundle object, the Bundle object is then stuffed into your activity's activity record by the OS.

Note that the types that you can save to and restore from a Bundle are primitive types and objects that implement the Serializable interface. When you creating custom classes, be sure to implement Serializable.

2. onPause()
3. onStop() 
   A stopped activity's survival is not guaranteed. When the system needs to reclaim memory, it will destroy stopped activities.
4. onDestroy()




No comments:

Post a Comment