Sobes.tech
Junior

What can you tell about the lifecycle of an Activity in Android?

sobes.tech AI

Answer from AI

The lifecycle of an Activity is a set of states and transitions between them that each Activity instance goes through from creation to destruction. It is defined by a set of callback methods.

Main lifecycle callback methods:

  • onCreate(): Called when the Activity is first created. UI initialization, data binding, and other one-time actions occur here.
  • onStart(): Called when the Activity becomes visible to the user but has not yet gained focus.
  • onResume(): Called when the Activity gains focus and becomes active. Animations and other interactive actions usually start here.
  • onPause(): Called when the Activity loses focus but is still visible (e.g., a semi-transparent dialog appears). Resource-intensive operations should be stopped here.
  • onStop(): Called when the Activity is no longer visible to the user. Unsaved data should be saved here, and resources no longer needed should be released.
  • onDestroy(): Called before the Activity is destroyed. All remaining resources should be released here.
  • onRestart(): Called after onStop() when the Activity is being redisplayed. Followed by onStart().

Graphically, the lifecycle can be represented as:

Created -> Started -> Resumed -> Paused -> Stopped -> Destroyed

Transitions also exist:

  • Created -> Started (after onStart())
  • Started -> Resumed (after onResume())
  • Resumed -> Paused (when losing focus)
  • Paused -> Resumed (when regaining focus)
  • Paused -> Stopped (when fully hidden)
  • Stopped -> Destroyed (when activity finishes)
  • Stopped -> Restarted -> Started (after onRestart())

It is important to manage the Activity state correctly in these callback methods to avoid memory leaks and ensure proper app behavior during configuration changes or activity switches. To save state, onSaveInstanceState() is used (before onStop()), and restoration occurs in onCreate() or onRestoreInstanceState() (after onStart()).

Example of using onSaveInstanceState():

// Saving state
override fun onSaveInstanceState(outState: Bundle) {
    outState.putString("my_data", "some_value")
    super.onSaveInstanceState(outState)
}

// Restoring state
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // ...
    if (savedInstanceState != null) {
        val myData = savedInstanceState.getString("my_data")
        // Use myData
    }
}