I would like to record the learning process with articles, and please indicate if there are any mistakes.
Activity life cycle
First put the complete life cycle diagram of Activity in Google Develop Guides:
Preliminary interpretation of callback
onCreate()
: Called when an activity is created.onStart()
: Called when the activity enters a visible state, making the activity visible but not user-interactive.onResume()
: Called when the activity enters the foreground and can interact with the user.onPause()
: Called when the activity does not hold user focus but is still visible. The activity is still visible, but stops interacting with the user, such as popups, lockscreens, etc.onStop()
: called when the activity is not visibleonDestroy()
: Activity exits, called when it is destroyedonRestart()
: Called when the activity returns to the foreground from being invisible. CallonRestart()
->onStart()
-> in turnonResume()
Actions performed in the callback method
onCreate()
: In this method, perform basic application startup logic, which should only happen once during the activity's entire lifetime. Such as binding data toListView
, declaring scoped variables, etc. At the same time, the method receives asavedInstanceState
parameter, which is used to restore the object of the previously saved stateBundle
. We will introduce it later.onStart()
: In this method, components that maintain the UI are initialized, such as registering a broadcast that monitors UI changes.onResume()
: In this method, you should initializeonPause()
the components released in the middle, such as initializationcamera
, and perform the initialization operations that are required each time the activity enters the foreground, such as starting animation and initializing which components only need to be obtained when the user focus is obtained, such as context menu.onPause()
: Free up system resources such as broadcast receivers, processing sensors (egGPS
), or anything that might affect battery life.onStop()
: Release almost all unneeded resources, such asonStart()
the broadcast created above, and perform time-consuming resource release operations in this method, such as saving data, network calls, database transactions, etc. It is also important to free resources that could lead to memory leaks in this method, because the lastonDestroy()
method will not be called when the system kills the active process due to memory tightness.onDestroy()
: ReleasesonCreate()
global resources that can be used by activities initialized in .When a method is called in any lifecycle callback method
finish()
, the system will directly callonDestroy()
the method and skip all previous callback processes.onRestart()
: Due toonStart()
the existence of this method, there seems to be no usage scenarios for this method.
Why onStop()
release time-consuming resources in but not in onPause()
?
Reason: In two Activity A and B, when A startActivity()
or startActivityForResult()
B is started, the callback methods of the lifecycle are called in the following order:
Activity A's
onPause()
Activity B's
onCreate()
,onStart()
, areonResume()
executed in sequence, at this point Activity B enters the foreground and gets user focus >* If Activity A is no longer displayed on the screen, itsonStop()
method is called.
A series of methods such as A's onStop()
method and B's onCreate()
method are not executed sequentially, but overlap. Therefore, when onPause()
time-consuming operations are performed in the method, it will seriously affect the jump speed between activities .
The calling sequence of callback methods in different scenarios
Start Activity
onCreate()
(create) ->onStart()
(visible, not interactive) ->onResume()
(foreground, interactive)currentActivity is partially covered by otherActivity, or lock screen
onPause()
(loses user focus, but is still visible)currentActivity returns to the foreground or unlocks the screen from the invisible state of the above part
onResume()
(foreground, holding the user focus)currentActivity goes to otherActivity interface, or press Home to return to the main interface, and enters the background by itself
onPause()
(loses user focus, but is still visible)—>onStop()
(invisible)Open the activity again from the above background state
onRestart()
(transition state, not sure what the use is...) —>onStart()
(visible, not interactive) —>onResume()
(foreground, holding user focus)When the currentActivity is partially visible or the background is not visible, and the system memory is insufficient, the current Activity will be
killed , and no callback will occur in the life cycle at this time.The above killed activity is started again
onCreate()
(recreated) —>onStart()
(visible, not interactive) —>onResume()
(foreground, holding user focus)User exits currentActivity
onPause()
(loses user focus, but is still visible) —>onStop()
(invisible) —>onDestroy()
Under multiple windows, when ActivityA gets the focus, click on ActivityB
For ActivityA:onPause()
(lose user focus, but still visible)
For ActivityB:onResume()
(foreground, hold user focus)
Fragment life cycle
Similarly, put the complete lifecycle diagram of Fragment in Google Develop Guides first:
Callback parsing
The method of the same name in Activity will not be repeated
onAttach()
Called when Fragment and Activity are associated (get the value passed by the activity, such as when the two rely on callback communication, get the reference of the activity (transform it into a callback callback interface))onCreateView()
Called when a view is created for a Fragment (the layout is loaded) (the UI layout is drawn for the current fragment, and the UI can be updated using threads)onActivityCreated()
onCreate()
Called when the method in the Activity is executed (indicatesoncreate()
that this method is called when the activity execution method is completed)onDestroyView()
Called when the layout in the Fragment is removedonDetach()
Called when Fragment and Activity are disassociated
The calling sequence of callback methods in different scenarios
When creating a fragment, the
creation process:onAttach()
—>onCreate()
—>onCreateView()
—>onActivityCreated()
display to the foreground:onStart()
—>onResume()
fragment goes into background
onPause()
-->onStop()
fragment is destroyed
onPause()
—>onStop()
—>onDestroyView()
—>onDestroy()
—>onDetach()
lock screen
onPause()
—>onStop()
Unlock—
onStart()
>onResume()
Open other fragments (the original fragment is replaced, or is completely invisible)
onPause()
—>onStop()
—>onDestroyView()
Back to the original fragment under the above conditions
onCreateView()
—>onActivityCreated()
->onStart()
—>onResume()
HomeBack to desktop—
onPause()
>onStop()
The above goes back to the original fragment
onStart()
—>onResume()
Exit application
onPause()
—>onStop()
—>onDestroyView()
—>onDestroy()
—>onDetach()
The relationship between the life cycle of the two
The old rule is to put the comparison chart in Google Develop Guides.
Due to the internal mechanism of Android (the principle is not known, and the source code has not been studied in depth), the fragment always exists depending on the activity, but it should be noted that the life cycle of the activity is controlled by the system , and the fragment is controlled by the host activity, so when the activity enters a certain state such as created, the system will call the activity, and the onCreate()
host activity will call the fragment's onAttach()
... onActivityCreated()
A series of methods, so that the fragment can quickly keep up with the host, and the host activity maintain a consistent state.
About Activity state saving and restoration
In the above life cycle, we sometimes need to save the state of the activity. For example, when we are entering text in a text box EditText, when we exit the application and open it again, we will find that the content of the text box disappears. Disappeared. . Disappeared. . .
In this case, the user experience will obviously not be good. So Google introduced the concept of saving UI state.
save state
Rewrite onSaveInstanceState()
, pass in an Bundle
object with state information, the code is as follows:
static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
// ...
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
When to save state
Called when the Activity is easily destroyed:
- Press
Home
the key: Activity enters the background - Lock screen: Activity enters the background
- Start other Activity: Activity enters the background
- Horizontal and vertical screen switching: destroy and rebuild the Activity instance
In the above scenarios, most of the low-priority activities in the background may be destroyed when the system memory is insufficient.
Precautions
The state is not saved when the user actively destroys the Activity:
*back
key
* callfinish()
methodMethod call timing:
* Before Android P:onStop()
Before, but not sureonPause()
before or after.
* Android P:onStop()
called afterA component with an id will automatically save the state of the component
recovery state
We have two ways to restore the state:
- It should be noted in the method
onCreate()
recovery that when trying to read the object, it is necessary to determine whether it is empty. If it is empty, a new instance of the activity will be created, rather than the instance of the activity that was destroyed before recovery:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} else {
// Probably initialize members with default values for a new instance
}
// ...
}
- Overriding
onRestoreInstanceState()
method restore
is only called by the system when there is a state to restoreonRestoreInstanceState()
, so there is no need to checksavedInstanceState
for null:
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}
call timing
- Called when rebuilding after destruction, if the memory is sufficient and the system has not destroyed the Activity, there is no need to call
- Called when the horizontal and vertical screens are switched
Summarize
- This article analyzes the life cycle of Activity and Fragment, as well as the state preservation and restoration of Activity as detailed as possible
- The author's level is limited, if there are any mistakes or omissions, please correct me.
- Next, I will also share the knowledge I have learned. If you are interested, you can continue to pay attention to the Android development notes of whd_Alive.