The Android lifecycle is a series of states through which an Android application progresses during its execution. Understanding these states is essential for managing resources efficiently and ensuring a smooth user experience.
An Android app has multiple components, with Activity and Fragment being the most common. Each of these components has a defined lifecycle managed by the Android operating system.
The activity lifecycle consists of the following methods:
-
onCreate()
- Called when the activity is first created.
- Used for initialization, such as setting the layout and initializing variables.
-
onStart()
- Called when the activity becomes visible to the user.
-
onResume()
- Called when the activity starts interacting with the user.
- The app is now in the foreground and the user can interact with it.
-
onPause()
- Called when the system is about to resume another activity.
- Use this method to pause operations such as animations or sensor updates.
-
onStop()
- Called when the activity is no longer visible to the user.
-
onRestart()
- Called when the activity is being restarted after being stopped.
-
onDestroy()
- Called before the activity is destroyed.
- Use this method to release resources and clean up tasks.
- App Launch →
onCreate
,onStart
,onResume
- App Minimize →
onPause
,onStop
| App Restore →onRestart
,onStrat
,onResume
- Open Another Activity →
onPause
,onStop
| Back →onRestart
,onStart
,onResume
- App Orientation Change →
onPause
,onStop
,onDestroy
,onCraete
,onStart
,onResume
Fragments have a similar but slightly extended lifecycle compared to activities:
-
onAttach()
- Called when the fragment is associated with its activity.
-
onCreate()
- Called to initialize the fragment.
-
onCreateView()
- Called to create and return the fragment's UI.
-
onViewCreated()
- Called after the fragment's view is created.
-
onStart()
- Called when the fragment becomes visible.
-
onResume()
- Called when the fragment starts interacting with the user.
-
onPause()
- Called when the fragment is no longer interacting with the user.
-
onStop()
- Called when the fragment is no longer visible.
-
onDestroyView()
- Called when the fragment's view is destroyed.
-
onDestroy()
- Called when the fragment is being destroyed.
-
onDetach()
- Called when the fragment is detached from its activity.
- Always release resources such as database connections, threads, or listeners in
onStop()
oronDestroy()
. - Save the state of the activity in
onSaveInstanceState()
to restore it later. - Use
ViewModel
orLiveData
to manage data efficiently and persist it across configuration changes. - Avoid lengthy operations on the main thread. Use background threads or
AsyncTask
for such tasks.
- Android Developer Documentation: Activity Lifecycle
- Android Developer Documentation: Fragment Lifecycle
Happy coding! 🎉