Junior — Middle
Can you explain the stages of the Activity component lifecycle in Android?
sobes.tech AI
Answer from AI
The lifecycle of an Activity component in Android consists of several main stages, each corresponding to specific methods:
- onCreate() — called when the Activity is created. Initialization of components and setting up the interface occur here.
- onStart() — the Activity becomes visible to the user.
- onResume() — the Activity starts interacting with the user (comes to the foreground).
- onPause() — called when the Activity loses focus but is still visible (e.g., a dialog appears).
- onStop() — the Activity is no longer visible to the user.
- onDestroy() — the final stage, when the Activity is destroyed by the system.
- onRestart() — called if the Activity returns from the stopped state to started.
These methods help manage resources and the application's state, such as saving data when leaving the screen and restoring it upon return.
Example of simple method overriding in an Activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onPause() {
super.onPause();
// Save state or stop animations
}
@Override
protected void onResume() {
super.onResume();
// Restore state or start animations
}
Understanding the lifecycle helps create robust and efficient applications.