乐闻世界logo
搜索文章和话题

What are the lifecycle methods of Android Activity and when are they triggered

3月6日 23:09

Android Activity Lifecycle

Activity lifecycle is a core concept in Android interviews. Understanding it is crucial for building stable applications.

Complete Lifecycle Methods

1. onCreate()

  • Trigger: When Activity is first created
  • Purpose: Initialize UI, restore state, set layout
  • Note: Activity is not yet visible

2. onStart()

  • Trigger: When Activity is about to become visible
  • Purpose: Register receivers, start animations
  • Note: Activity doesn't have focus yet

3. onResume()

  • Trigger: When Activity gains focus and can interact with user
  • Purpose: Start camera, location services requiring focus
  • Note: Activity is in foreground

4. onPause()

  • Trigger: When Activity loses focus but is still partially visible
  • Purpose: Save critical data, stop animations, release resources
  • Note: Must execute quickly to avoid blocking next Activity

5. onStop()

  • Trigger: When Activity is completely invisible
  • Purpose: Release resources, unregister receivers, stop location
  • Note: May be killed by system

6. onDestroy()

  • Trigger: Before Activity is destroyed
  • Purpose: Final cleanup
  • Note: Distinguish normal destruction from config change

7. onRestart()

  • Trigger: When Activity restarts from stopped state
  • Purpose: Restore state before stopping

Typical Scenario Lifecycle Flow

ScenarioLifecycle Flow
First launchonCreate → onStart → onResume
Navigate to other ActivityonPause → onStop
Return to ActivityonRestart → onStart → onResume
Press HomeonPause → onStop
Screen rotationonPause → onStop → onDestroy → onCreate → onStart → onResume
System killDirect onDestroy, no callback

Key Points

  • Restore data in onCreate and onRestoreInstanceState
  • Don't perform long operations in onPause
  • Use ViewModel to prevent data loss during config changes
标签:Android