Activity lifecycle methods help your app know what to do when the screen opens, closes, or changes. They keep your app working smoothly and save resources.
Activity lifecycle methods (onCreate, onStart, onResume, onPause, onStop, onDestroy) in Android Kotlin
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Initialize your activity here
}
override fun onStart() {
super.onStart()
// Activity is becoming visible
}
override fun onResume() {
super.onResume()
// Activity starts interacting with the user
}
override fun onPause() {
super.onPause()
// Activity is partially visible, pause ongoing actions
}
override fun onStop() {
super.onStop()
// Activity is no longer visible
}
override fun onDestroy() {
super.onDestroy()
// Clean up resources before activity is destroyed
}Each method calls super to keep the system working properly.
Methods run in a specific order as the activity moves through states.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}override fun onPause() {
super.onPause()
// Pause music or animations here
}override fun onDestroy() {
super.onDestroy()
// Release resources like database or sensors
}This example logs messages to the console each time a lifecycle method runs. You can watch these logs to understand when each method is called as you open, use, and close the app.
import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d("Lifecycle", "onCreate called") } override fun onStart() { super.onStart() Log.d("Lifecycle", "onStart called") } override fun onResume() { super.onResume() Log.d("Lifecycle", "onResume called") } override fun onPause() { super.onPause() Log.d("Lifecycle", "onPause called") } override fun onStop() { super.onStop() Log.d("Lifecycle", "onStop called") } override fun onDestroy() { super.onDestroy() Log.d("Lifecycle", "onDestroy called") } }
Use onCreate to set up your UI and initialize variables.
onPause and onStop are good places to save data or pause tasks.
onDestroy is the last chance to clean up before the activity is removed.
Activity lifecycle methods let your app respond to changes in screen visibility and user interaction.
Always call super in each lifecycle method to keep the system stable.
Use these methods to manage resources, save data, and keep your app smooth and efficient.