What is Activity lifecycle in Android SDK?

In Android SDK, the Activity lifecycle refers to the various states that an Activity can be in during its life from creation to destruction. Understanding the Activity lifecycle is crucial for effective app development, as it helps manage resources, user interactions, and application performance.

There are several key methods that are called at different points in the lifecycle:

  • onCreate(): Called when the Activity is first created. This is where initialization occurs and the user interface for the Activity is set up.
  • onStart(): Called when the Activity becomes visible to the user.
  • onResume(): Called when the Activity starts interacting with the user.
  • onPause(): Called when the Activity is partially obscured by another Activity or when the user navigates away from it.
  • onStop(): Called when the Activity is no longer visible to the user.
  • onDestroy(): Called before the Activity is destroyed.
  • onRestart(): Called when the Activity is being restarted after being stopped.

Managing these states properly ensures that your application performs optimally and provides a great user experience.

public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onStart() { super.onStart(); // Code that runs when the Activity is visible to the user } @Override protected void onResume() { super.onResume(); // Code to execute when the Activity is interacting with the user } @Override protected void onPause() { super.onPause(); // Code to execute when the Activity is not in focus } @Override protected void onStop() { super.onStop(); // Code to execute when the Activity is completely hidden } @Override protected void onDestroy() { super.onDestroy(); // Cleanup resources } }

Activity lifecycle Android lifecycle methods Android app development