Point
One, the life cycle of Activity
1. Classification of life cycle conditions
- The life cycle under normal circumstances (the life cycle experienced by the user in the case of participation)
- Life cycle under abnormal conditions (Acyivity is recycled by the system, or the configuration of the device is changed, causing the activity to be destroyed and rebuilt)
2. Life cycle diagram
ps: Picture source network
3. Life cycle under normal conditions:
7 types:
- onCreate
- onRestart
- onStart
- onResume
- onPause
- onStop
- onDestroy
onCreate : The first method of the life cycle, this method is the first to go when we open an activity.
What we can do: initialization work. Such as loading interface (setContentView), data initialization (findviewbyid, etc.)
onStart : indicates that the activity is being started.
Features: the activity is visible and does not appear in the foreground.
Understanding: Activity has been displayed, but we can't see it.
onResume : Indicates that the activity is already visible and appears in the foreground to interact with the user.
For example, there is a Button on the activity, and we can click it at this time.
The difference with onStart:
onStart is not visible in the foreground, so it is not interactive. onResume is visible in the foreground, so you can interact.
onPause : Indicates that the activity is stopping, and then execute onStop soon.
Note: In extreme cases, jump to other activities and quickly return to the current activity. The life cycle of the current activity: onPause->onResume
but this "quick return" requires Soon, usually onPause->onStop->onRestart->onStart->onResume
ps: You can’t do too time-consuming operations here, you can do some data storage, and the animation stops.
onStop : Indicates that the activity is about to stop.
onRestart : The current activity is restarting, usually caused by user behavior, such as the user switching Activity, or press the home button to return to the desktop, when the user returns to this activity again, the current activity goes onRestart->onStart->onResume
onDestroy : The activity is about to be destroyed, the last callback in the activity life cycle, where you can do some recycling work and release resources.
4. The switching process of the life cycle under normal circumstances
Here is the interpretation of the following two activities:
MainActivity: There are seven life cycle callbacks, and a button.
Main2Activity: Seven life cycle callbacks
The code is as follows (for these two activities, the next switching process)
MainActivity:
public class MainActivity extends AppCompatActivity {
public static final String TAG = "tags";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Main2Activity.class));
}
});
Log.i(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "onStart");
}
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "onStop: ");
}
@Override
protected void onRestart() {
super.onRestart();
Log.i(TAG, "onRestart: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy: ");
}
}
Main2Activity
public class Main2Activity extends AppCompatActivity {
public static final String TAG = "tags";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
setContentView(R.layout.activity_main2);
Log.i(TAG, "Main2Activity onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "Main2Activity onStart");
}
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "Main2Activity onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "Main2Activity onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "Main2Activity onStop: ");
}
@Override
protected void onRestart() {
super.onRestart();
Log.i(TAG, "Main2Activity onRestart: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "Main2Activity onDestroy: ");
}
}
(1) When MainActivity is started for the first time:
MainActivity experienced: onCreate->onStart->onResume
(2) When jumping from mainactivity to Main2Activity:
MainActivity went through: onPause->onStop
ps: When MainActivity goes onPause, the new Main2Activity will go first: Main2Activity onCreate -> Main2Activity onStart -> Main2Activity onResume Then MainActivity goes ->onStop
emphasizes:
1. If Main2Activity has been set to be transparent at this time For the theme, mainActivity does not go onStop, only onPause. Jumping from MainActivity to Main2Activity we can still see mainActivity, so we verified that onPause is visible and not in the foreground.
2. The display dialog box does not affect the life cycle.
(3) Press the Home button in MainActivity
MainActivity 走onPause->onStop
(4) When you return to MainActivity after pressing Home
At this time MainActivity went onRestart->onStart->onResume
(5) Start mainActivity to jump to Main2Activity, and then return to mainActivity
As above:
1 corresponds to start mainActivity
2 corresponds to jump to Main2Activity
3 corresponds to return to mainActivity
(6) When the user opens the mainactivity and presses the back key
mainActivity is gone onPause->onStop->onDestroy
5. Life cycle analysis
From the entire life cycle, onCreate and onDestroy are paired, representing the creation and destruction of actiity respectively. And it can only be called once.
From whether the activity is visible, onStart and onStop are paired, and the two life cycles may be executed multiple times as the user operates.
From whether the activity is in the foreground, onResume and onPause are paired, and the two life cycles may be executed multiple times as the user operates.
6. Question thinking
Question 1: OnStart and onResume, onPause and onStop are similar in description to us. What are the substantial differences?
From the use process, the two pairs are indeed similar, and we can even keep only one pair, such as only onStart and onStop. In that case, why does the Android system provide seemingly repetitive excuses? According to the above analysis, we know that these two pairs of interfaces represent different meanings. onStart and onStop are called back from the perspective of visibility (the former is visible and the latter is not visible).
onResume and onPause are called back from the perspective of whether it is the foreground (the former is the foreground, the latter is not the foreground)
Question 2: Assuming that the current activity is A, if the user opens a new activity B at this time, the onResume of B and the onPause of A will be executed first
Execution result A: onPause->B:onCreate->B:onStart->B:onResume->A:onStop
1: Case derivation reference: 4, (2) above
2: Find the answer in the source code of the activity startup process. (Omitted, see Android Development Art Exploration)
7. Life cycle under abnormal conditions
Life cycle under abnormal conditions:
- Resource-related system configuration changes
- Insufficient system memory
7.1, the resource-related configuration changes cause the Activity to be killed and recreated
For example, if the current activity is in a portrait state, if the screen is suddenly rotated due to a change in system configuration, the activity will be destroyed and rebuilt by default. Of course, we can also prevent the system from recreating our activity.
Chestnut: We open activity by default
Rotate the screen at this time:
OnSaveInstanceState and onRestoreInstanceState are the two activity callback methods I added. We can see that the activity is first destroyed and then re-established.
7.1.1. Data storage under abnormal conditions:
In fact, activity also has two methods onSaveInstanceState, onRestoreInstanceState. Used to store data under abnormal conditions.
- onSaveInstanceState(Bundle outState) When the
activity terminates abnormally, the system will call this method to save the state of the activity. We can also store the information we want to save when the abnormal termination occurs here. (Note that this method will not call back when the activity terminates normally) - onRestoreInstanceState(Bundle savedInstanceState)
When the activity is abnormally terminated and rebuilt, the system will call this method, and pass the Bundle object saved by onSaveInstanceState when the activity is destroyed as a parameter to onCreate and onRestoreInstanceState, so we can determine whether the activity has been rebuilt through the onCreate and onRestoreInstanceState methods . If it is reconstructed, we can retrieve the previously saved data.
At the same time, we know that in the onSaveInstanceState and onRestoreInstanceState methods, the system automatically does some restoration work for us. When the activity is recreated under abnormal conditions, the system defaults to saving the view structure of the current activity for us. And resume these tasks for us when the activity is re-created. For example, the data entered in the text box, the position where the ListView scrolls to, etc., the state system related to these views will be stored for us by default and restored. But which view system can help us restore which data depends on the source code of a view (view has these two methods for callbacks like activity)
For saving and restoring the view hierarchy, the delegation idea is adopted (see Android Development Art)
Examples of EditText data recovery under abnormal conditions:
Write callback is used to restore the data we want to save
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.i(TAG, "onSaveInstanceState: ");
outState.putString("tom","异常下存数据 :tom");
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.i(TAG, "onRestoreInstanceState: ");
Log.i(TAG, " "+savedInstanceState.get("tom"));
}
A text input box (data that the test system automatically responds to us):
Rotate the screen after typing:
You can see that the data is restored after the callback is gone. The data system in editText helps us to restore, and our customized data is also restored.
ps: pay special attention to our EditText must set the id in the xml layout, otherwise the data will not be restored Recovery (pro-test, see EditText source code for reasons)
We store data in onSaveInstanceState, which can be accepted in both onRestoreInstanceState and onCreate. The reception difference is as follows:
- onRestoreInstanceState
Once called its arguments savedInstanceState there must be some value, we do not have additional sentence empty.
If onCreate is started normally, its parameter value is empty, so it needs to be extra blank.
7.2. Insufficient resource memory causes low priority activities to be killed
This situation is not easy to simulate, but the data storage and recovery process and the resource configuration change callback are exactly the same
Here are the priority levels of activity:
- The activity
that the foreground activity is interacting with the user has the highest priority. - Visible but non-foreground activity,
such as a pop-up dialog box in the activity, causes the activity to still be visible, but cannot interact with the user, and the priority is inferior to the foreground. - The background activity
has been stopped, such as onstop. The lowest priority.
When the system memory is insufficient, the system will kill the process where the target activity is located according to the above priority. And through, onSaveInstanceState, onRestoreInstanceState to store and restore data.
If there are no four components in a process (empty process), the process will be killed by the system soon. Therefore, some background work is not suitable for running in the background alone without the four major components, which can easily be killed. A better way is to put the background work in the Service to ensure that the process has a certain priority, so that it will not be easily killed by the system.
ps: Process in Android (priority from high to low): foreground>visible>service process>background process>empty process
8. Prohibit activity re-creation under abnormal conditions
The above describes the activity will be re-created under abnormal circumstances, so can the activity be prevented from being re-created? The answer is that some assign the configChanges attribute to the activity. (as follows)
The attribute values of configChanges are as follows:
Attribute value | meaning |
---|---|
mcc | The country code in the SIM card's unique identification IMSI (International Mobile Subscriber Identity) is composed of a three-dimensional array, and China is 460. The mcc code of this identification has changed |
mnc | The SIM card uniquely identifies the operator code in the IMSI (International Mobile Subscriber Identity), which is composed of two digits. The TD system of China Mobile is 00, China Unicom is 01 and China Telecom is 03. The mnc code of this identification has changed |
locale | The local location of the device has changed, generally means that the system language has been switched |
touchscreen | The touch screen has changed, this can be ignored, it will not happen under normal circumstances |
keyboard | The keyboard type has changed. For example, the user has inserted an external keyboard. |
keyboardHidden | The accessibility of the keyboard has changed. For example, the user brings up the keyboard |
navigation | Changes in system navigation methods, such as trackball navigation, are difficult to occur and can be ignored |
screenLayout | The screen layout has changed, it is possible that the user has activated another display device |
fontScale | The system font scaling has changed, for example, the user selects a new font size |
uiMode | The user interface mode has changed, such as whether night mode is turned on (newly added in api 8) |
orientation | The screen orientation changes, this is the most commonly used, such as rotating the phone screen |
screenSize | When the screen size information changes, when the device screen is rotated, the screen size will change. This option is special, and it is related to the compilation option. When the minSdkVersion and targetSdkVersion in the compilation options are both lower than 13, this option will not cause activity Restart, otherwise the activity will restart (newly added in api 13) |
smallestScreenSize | When the physical screen size information of the device changes, this attribute value has nothing to do with the orientation of the screen. It only means that the actual physical screen changes, such as when the user switches to the peripheral display device. Same as screenSize, when the minSdkVersion in the compiler option When both and targetSdkVersion are lower than 13, this option will not cause the activity to restart, otherwise it will cause the activity to restart (newly added in api 13) |
layoutDirection | When the layout direction changes, this attribute is less used. Under normal circumstances, the layoutDirection cannot be modified (newly added in api 17) |
ps: We can configure multiple values of the above attributes, just use | to connect.
From the above table, we find that if we do not specify the specific attribute value of configChanges for the Activity, the activity will be recreated under abnormal circumstances. There are many attribute values in the above table, but there are only a few commonly used -> locale, orientation, keyboardHidden. It should be noted that screenSize, smallestScreenSize is only related to the compiled version, and has nothing to do with the operating environment.
chestnut:
Add onConfigurationChanged callback for activity
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.i(TAG, "onConfigurationChanged: ");
}
Manifest file configuration:
rotating screen:
We found that the activity did not destroy and rebuild after rotating the screen but went onConfigurationChanged method.
summary
This section is not finished: this chapter only summarizes the life cycle of activity. Activity startup mode, intentFliter matching rules have not been summarized, please refer to the summary of the remaining two parts:
Activity life cycle and startup mode (2)
The end
Read <Android Development Art Exploration> Practice Summary