Activity Lifecycle
Activity Lifecycle
Every activity and every fragment have what's known as a lifecycle. So this lifecycle is made of different states from the initialisation to the destruction.
Activity Lifecycle States :It represents the current status of the Activity. Like is it visible or not ? Has the user permanently navigated away?
- Created
- Started
- Resumed
- Destroyed
- Initialised
Activity Lifecycle Callback method:
- onCreate - called once when the activity if first launched
- onStart - called when activity is visible
- onResume - called when activity has focus
- onDestroy - called when you press back button and navigate to another activity
- onPause - called when activity losses focus
- onStop - called when activity goes offscreen
- onRestart - if activity is already created it is called before the activity becomes visible it's like onCreate
OnResume and onPause() has to do with concept of focus, having focus is when you can actually interact with the activity.
- This methods are called when the activity moves from one state to another.
- If we want to change the behaviour or run some code when the activity lifecycle state changes, any activity or it's subclass have these activity lifecycle callback methods.
- You can perform an action when the activity enters a certain lifecycle state by overriding these callback methods.
- It's important to know both when they are called and what to do at each callback.
Garbage Collection:
In onDestroy() the activity is fully shutdown and could be garbage collected. Garbage Collection is a technical term that refers to automatic cleanup of objects that you're no longer going to use.
// lifecycle methods
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Timber.i("Timber Logging: onCreate called ")
}
override fun onStart() {
super.onStart()
Timber.i("Timber Logging : onStart called ")
}
override fun onResume() {
super.onResume()
Timber.i("Timber Logging : onResume called ")
}
override fun onPause() {
super.onPause()
Timber.i("Timber Logging : onPause called ")
}
override fun onStop() {
super.onStop()
Timber.i("Timber Logging : onStop called ")
}
override fun onDestroy() {
super.onDestroy()
Timber.i("Timber Logging : onDestroy called ")
}
override fun onRestart() {
super.onRestart()
Timber.i("Timber Logging : onRestart called ")
}
Use Case :
- Click Back Button : onPause(), onStop(), onDestroy()
- Click Share Button : onPause(), onResume()
Comments
Post a Comment