Sobes.tech
Junior

What lifecycle methods of Activity do you know and how are they executed?

sobes.tech AI

Answer from AI

  • onCreate(): Called when the Activity is first created. Used for initializing UI and data.
  • onStart(): The Activity becomes visible to the user.
  • onResume(): The Activity becomes active and is on the foreground. The user can interact with it.
  • onPause(): Called when the Activity goes to the background or another Activity partially closes it. Used for saving state that needs to be quickly restored.
  • onStop(): The Activity is no longer visible to the user. Used for releasing unused resources.
  • onDestroy(): Called before the Activity is destroyed. Used for final cleanup of resources.
  • onRestart(): Called after onStop(), when the Activity becomes visible again.

Sequence of method execution on startup: onCreate() -> onStart() -> onResume().

Sequence of method execution when transitioning to background (e.g., pressing the Home button): onPause() -> onStop().

Sequence of method execution when returning from background: onRestart() -> onStart() -> onResume().

Sequence of method execution when destroying an Activity: onPause() -> onStop() -> onDestroy().

On screen rotation, the Activity is destroyed and recreated. Sequence: onPause() -> onStop() -> onDestroy() -> onCreate() -> onStart() -> onResume(). To save state, onSaveInstanceState() (called before onStop()) is used, and restoration occurs in onCreate() or onRestoreInstanceState() (called after onStart()).

class MyActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main) // UI initialization
        // Restoring state from savedInstanceState
    }

    override fun onStart() {
        super.onStart()
        // Activity becomes visible
    }

    override fun onResume() {
        super.onResume()
        // Activity is on the foreground, available for interaction
    }

    override fun onPause() {
        super.onPause()
        // Activity goes to the background
        // Saving quickly restorable state
    }

    override fun onStop() {
        super.onStop()
        // Activity is not visible
        // Releasing resources
    }

    override fun onDestroy() {
        super.onDestroy()
        // Activity is destroyed
        // Final cleanup of resources
    }

    override fun onRestart() {
        super.onRestart()
        // Activity returns from background
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        // Saving state before destruction
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        // Restoring state
    }
}