Article directory
1. Learning objectives
- Understand the Activity life cycle diagram
- Master life cycle callback methods
- Use the log class Log to output information
2. Learning new lessons
(1) Activity life cycle
1. Understand the activity life cycle
- As users browse, exit, and return to your app, Activity instances in your app transition between different states in their life cycle. The Activity class provides many callbacks that let the Activity know that a certain state has changed: the system is creating, stopping, or resuming an Activity, or the process in which the Activity is located is being destroyed.
- In the lifecycle callback methods, you can declare how the activity behaves when the user leaves and re-enters the activity. For example, if you are building a streaming video player, you might want to pause the video or terminate the network connection when the user switches to another app. When the user returns, you can reconnect to the network and allow the user to continue playing the video from the same location. In other words, each callback enables you to perform a specific job appropriate for a given state change. Executing the right job at the right time and handling transitions appropriately will improve the robustness and performance of your application. For example, a good lifecycle callback implementation can help prevent your app from:
– Crashing when the user answers a call while using the app, or switches to another app.
– Consumes valuable system resources when the user is not actively using it.
– Lose the user’s progress when the user leaves the app and returns later.
– Crash or lose user progress when the screen is rotated between landscape and portrait.
2. Simplified diagram of Activity life cycle
- To navigate between the various stages of the Activity life cycle, the Activity class provides six core callback methods:
onCreate()
,onStart()
,onResume()
,onPause()
,onStop()
andonDestroy()
. Each of these callback methods is called when the activity enters a new state.
(1) Whether Activity exists or not
- The entire activity life cycle
onCreate()
starts with the method andonDestroy()
ends with the final method call. The global resources of the ActivityonCreate()
are set in the method, andonDestroy()
the resources are eventually recycled in the method.
(2) Whether the Activity is visible or not
The Activity is visible after triggering onStart()
the method, but may not be able to interact with the user. The method is triggered when the Activity is completely invisible onStop()
. When it becomes visible again, onRestart()
the method is triggered first, then onStart()
the method. onStart()
Methods and onStop()
methods can be called multiple times.
(3) Whether the Activity can be interacted with or not
Activity is active between the onResume() method and the onPause() method, and can interact with the user at this time.
3. Android process priority
- The life cycle of an application is all stages of the process in the Android system from startup to termination, that is, the entire process of Android from startup to stop. The end of the life cycle of an Android application is not performed by the application process itself, but depends on the Android system. So, what importance criteria does the system use to terminate Android applications? Android divides all processes into five categories from high to low according to the components of the application and the current running status of the components, as shown in the following figure:
(2) Activity life cycle callback method
1. onCreate() callback method
- You must implement this callback, which is triggered when the activity is first created by the system. After the activity is created, it enters the "Created" state. In the onCreate() method, you perform basic application startup logic, which should only occur once in the entire life cycle of the Activity. For example, an implementation of onCreate() might bind data to a list, associate an Activity with a ViewModel, and instantiate some class scope variables. This method receives the savedInstanceState parameter, which is a Bundle object containing the Activity's previously saved state. If the Activity did not exist before, the value of the Bundle object is null.
- If you have a lifecycle-aware component associated with your Activity lifecycle, the component will receive the ON_CREATE event. Methods annotated with @OnLifecycleEvent are called, allowing your lifecycle-aware component to execute any setup code required for the created state.
2. onStart() callback method
-onCreate() After exiting, the Activity will enter the "Started" state and be visible to the user. This callback contains the final preparations before the Activity enters the foreground and interacts with the user.
3. onResume() callback method
- The system calls this callback before the activity starts interacting with the user. At this point, the activity is at the top of the activity stack and captures all user input. Most of the core functionality of the application is implemented in the onResume() method.
- The onResume() callback is always followed by the onPause() callback.
4. onPause() callback method
- When an Activity loses focus and enters the "Paused" state, the system calls onPause(). For example, this state occurs when a user taps the Back or Recent Apps button. When the system calls onPause() for your activity, it technically means that your activity is still partially visible, but most of the time, it indicates that the user is leaving the activity and the activity will soon go to "stopped" ” or “Restored” status.
- If the user wants the interface to continue to update, the Activity in the "Paused" state can also continue to update the interface. For example, an activity that displays a navigation map screen or plays a media player would be such an activity. Even if such an Activity loses focus, users still expect its interface to continue to update.
- You should not use onPause() to save application or user data, make network calls, or perform database transactions. For information about saving data, see Saving and Restoring Activity State.
- After onPause() completes execution, the next callback is onStop() or onResume(), depending on what happens after the Activity enters the "Paused" state.
5. onStop() callback method
- When the Activity is no longer visible to the user, the system calls onStop(). This may occur because the activity is destroyed, a new activity is started, or an existing activity is entering the "Resume" state and overwrites the stopped activity. In all these cases, the stopped activity will no longer be visible at all.
- The next system callback will be onRestart() (if the Activity re-interacts with the user) or onDestroy() (if the Activity terminates completely).
6. onRestart() callback method
- This callback is called when the activity in the Stopped state is about to be restarted. onRestart() resumes the Activity from the state it was in when it was stopped.
- This callback is always followed by onStart().
7. onDestroy() callback method
- The system calls this callback before destroying the Activity.
- This callback is the last callback received by the Activity. Typically, onDestroy() is implemented to ensure that all resources of the Activity are released when the Activity or the process containing the Activity is destroyed.
(3) Use Log class to output information
- When debugging code, if you need to view debugging information, you need to use Android's android.util.Log class, which has 5 common methods. Note: When using different printing methods, they all carry (String tag, String msg) parameters. tag represents the label of the printed information, and msg represents the information that needs to be printed.
1. Log.v() method
- v: verbose; the output color is black, and any message will be output. The v here represents verbose. The usual use is Log.v("","");
2. Log.d() method
- d: debug; the output color is blue. Only debug information is output, but upper-layer information is output. Filtering can be selected through the Logcat tag of DDMS.
3. Log.i() method
- i: information; the output color is green, and general information is output. The information of Log.v and Log.d will not be output, but the information of i, w and e will be displayed.
4. Log.w() method
- w: warning; the output color is orange and warning information is output. Generally, we need to pay attention to optimizing the Android code. At the same time, after selecting it, Log.e information will also be output.
5. Log.e() method
- e: error; the output color is red, and only red error messages are displayed. We need to analyze carefully to find the cause of the error.
(4) Callback method case demonstration
1. Create an Android application
-
Based on Empty Activity template
-
Configure project information
-
Click the [Finish] button to complete project initialization
2. String resource file
strings.xml
Modifyapp_name
variable values in the file and add new variablestest_life_cycle
3. Main layout resource file
- Change the constraint layout to linear layout and set the related properties of the label control
4. Main interface class implementation function
-
MainActivity
Define tag constants inTAG
-
Output a debugging message in the onCreate and onDestroy callback methods
-
Output a debugging message in the onStart and onStop callback methods
-
Output a debugging message in the onResume and onPause callback methods
-
Output a debugging message in the onRestart callback method (in the process of being completely invisible⟹ \Longrightarrow⟹ completely visible)
-
View MainAcitivity source code
package net.xqf.lifecycle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private final static String TAG="life_cycle";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG,"onCreate invoked");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG,"onStart invoked");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG,"onResume invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG,"onPause invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "ononStop invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG,"onRestart invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy invoked");
}
}
5. Add message filter
- In order to better view the debugging information of this application, you need to add a message filter. Create the message filter life_cycle_filter and log the label as life_cycle
6. Start the application and view the logs
-
Start the application and view the messages in LogCat (then we switch the application state: foreground⟹ \Longrightarrow⟹background⟹ \Longrightarrow⟹ foreground⟹ \Longrightarrow⟹ closed)
-
Click the [Home] button to return to the mobile application desktop
-
At this time, the application window is covered by the desktop, view the log message
-
Click the [Overview] button to view the list of recent applications
-
The most recently opened application is [Life Cycle]
-
Click the [Life Cycle] application running in the background, and its window will return to the foreground to view the log information.
-
Pressing the [Back] button actually cannot close the [Life Cycle] application
-
You should press the [Overview] key, select the [Life Cycle] app and slide it up to close the app.
-
From the log information, we can see the three-tier architecture
- Outermost layer (onCreate - onDestory) - (exists - does not exist)
- Middle layer (onStart - onStop) - (visible - invisible)
- Innermost layer (onResume - onPause) - (interactive - not interactive)
- View operation screen recording