preface

Nice to meet you ~ welcome to read my article.

There are a lot of articles about the Activity lifecycle on the Web, and there are many blogs that talk about it quite well, which shows the importance of Activity is very high. In fact, I suspect that the first Android component every Android developer touches is an Activity. We start with the first Activity, run the code, and see a MainActivity title and a line of HolleWorld displayed on the simulator, opening the Android world.

This article focuses on the Activity lifecycle, and the design of the Activity will be covered at the end of the article. Different from other blog designs, the article uses a systematic explanation, about the Activity lifecycle related knowledge will be involved in the basic.

  • The first part of the article explains the cognition of Activity state;
  • Part 2 covers the activity lifecycle callback methods.
  • The third part analyzes the sequence of life cycle callbacks in different scenarios:
  • The fourth part is source code analysis;
  • The final part is to think about activities and their lifecycle from a higher perspective.

So, let’s get started.

Overview of life state

An Activity is a very important and complex component, and it does not start with a new object. It needs to go through a series of initializations. Examples are “just created state”, “background state”, “visible state”, etc. When we switch between screens, the activity also switches between various states, such as visible or invisible, foreground or background. When an Activity switches between different states, different lifecycle methods are called back. We can override these methods to execute the corresponding logic when entering different states.

There are nine states defined in the ActivityLifecycleItem abstract class. This abstract class, which has many subclasses, is the AMS transaction class that manages the Activity lifecycle. The Activity uses 6 of these directives (the setState method is not used to set the state of the other three). So here are the 6 kinds), as follows:

// When the Activity is first created
public static final int ON_CREATE = 1;
// Perform final preparations for transfer to the front desk
public static final int ON_START = 2;
// Finish the final preparations for the user interaction
// Now the activity is in the foreground
public static final int ON_RESUME = 3;
// When the user leaves, the activity enters the background
public static final int ON_PAUSE = 4;
// The activity is not visible
public static final int ON_STOP = 5;
// Perform final preparations before being destroyed
public static final int ON_DESTROY = 6;

Copy the code

The jump between states is not arbitrary. For example, you cannot jump from ON_CREATE to ON_PAUSE. AMS manages jumps between states. When the Activity switches between these states, the corresponding lifecycle is called back. The situation here is not easy to understand, so I drew a picture to help understand:

Here, the life state of an Activity is distinguished by three dimensions of “interactive”, “visible” and “existent”. Interactivity means whether it can operate with users. If it is visible, it indicates whether it is displayed on the screen. If it exists, the activity is killed by the system or the Finish method is called. Above the arrow is the method that will be called when entering the corresponding state. The switch between each state will not be discussed here, so that readers can better understand the activity state and state switch.

Note that the three dimensions used here are not very strict and are differentiated by combining with the overall display rules.

The onStart method is described in Google’s official documentation as follows: The onStart() call makes the Activity visible to the user because the application prepares the Activity for coming to the foreground and supporting interaction. This also fits into our dimensional distinction above. When an activity enters the ON_PAUSE state, it may still be visible, but not interactive. When operating on another application’s hover window, the current application’s activity enters the ON_PAUSE state.

But! During the activity launch process, the interface remains invisible until the onResume method is called. This will be explained in more detail later in the source code analysis. So the dimension of state distinction here is just a distinction in general, you could say, but it’s not very precise in the details. The reader needs to pay attention.

An important part of the lifecycle is to allow the logic to be executed when an activity switches between states. Here’s an example. We use camera resources in interface A. When we switch to the next interface B, interface A must release camera resources so that interface B will not be unable to use the camera. When we cut back to interface A, we want interface A to continue to have the state of camera resources. Then we need to release the camera resources when the interface is not visible, and get the camera resources again when the interface is restored. Each Activity can generally be thought of as an interface or screen. When we navigate between screens, we are actually switching activities. When the interface switches between states, that is, between Activity states, the activity-related methods are called back. For example, when the interface is not visible, the onStop method is called back, and when the interface is restored, the onReStart method is called back.

Doing the right job at the right time in the right life cycle makes the app more robust. Avoid crashes when the user jumps to another app, memory leaks, loss of progress when the user cuts back, loss of progress or crashes when the user rotates the screen, etc. These require us to have a certain understanding of the life cycle, in order to make the most correct choice in the specific scene.

This part of the overview does not focus on the lifecycle, but rather on understanding transitions between states, where lifecycle callbacks occur between different states. An important purpose of learning life cycle is to be able to do appropriate work in corresponding business scenarios, such as resource application, release, storage and recovery, so as to make app more robust.

Important lifecycle analysis

Google has a very important flowchart for the Activity’s important lifecycle callback method that everyone knows about. I’ve added some common callback methods to this diagram. These methods are not strictly an Activity lifecycle because they do not involve state switching, but they play a significant role in the Activity’s overall life cycle and are important callback methods. There are many ways. Let’s look at the picture and explain it one by one. When looking at the specific method of explanation, be sure to combine the following diagram with the diagram outlined in the previous section.

Major life cycle

First of all, let’s look at the seven most important life cycles. These seven life cycles are strictly life cycles that meet the key definition of state switching. This section is recommended to be understood in conjunction with the diagram in the overview section. (onRestart does not involve a state change, but because onStart is executed immediately after it is executed, it is also mentioned together.)

  • OnCreate: This method is called after the Activity instance is created and the Attach method is called to assign properties such as PhoneWindow and ContextImpl. This method is called only once during the entire Activity lifecycle. After calling this method, the Activity enters the ON_CREATE state.

    This method is one of the most frequently used callback methods.

    We need to initialize the underlying components and views in this method. Viewmodel, TextView. You must also call setContentView in this method to set the layout for the activity.

    This method takes a parameter that preserves data from the previous state. If it is the first startup, this parameter is null. This parameter comes from the data stored in onSaveInstanceState. The activity is called back only when it is temporarily destroyed and is expected to be recreated, such as when the screen rotates, when the background application is destroyed, and so on

  • OnStart: This method is called when the Activity is ready to come into the foreground. The Activity enters the ON_START state after the call.

    Be careful to understand the meaning of the front desk here. Although Google Docs states that the activity is visible after calling this method, as shown below:

    However, as we mentioned earlier, the foreground does not mean that the Activity is visible, only that it is active. ** This is one of the things that confuses me about Google Docs. (In fact, Google Docs lacks rigor in many places, perhaps sacrificing a little rigor for the sake of clarity).

    There is usually only one foreground activity, so this also means that all other activities go into the background. Here the front and back need to be combined with the activity return stack to understand, the author will write a follow-up on the return stack.

    This method is usually called when the activity is cut back from another activity.

  • OnResume: called when the Activity is ready to interact with the user. After the call, the Activity enters the ON_RESUME state.

    Note that this method is always considered a state in which the activity must be visible and ready to interact with the user. But that wasn’t always the case. If popupWindow is popped in the onReume method you will get an exception: token is null, indicating that the interface has not been added to the screen yet.

    However, this only happens when the activity is first started. When the activity starts, the decorView already has the token, and popping popupWindow again in the onReume method should not be a problem.

    Therefore, whether the activity is visible when onResume is called differentiates whether the activity was created for the first time.

    The onStart method is the distinction between background and foreground, and this method is the distinction between interactivity. At most, when a window for another activity pops up, the original activity enters the ON_PAUSE state but is still visible. When you return to the original activity, the onResume method is called back.

  • OnPause: This method is called when the current activity window loses focus. After the call, the activity enters the ON_PAUSE state and enters the background.

    This method is usually called before another activity is about to enter the foreground. Other activities can enter the foreground only if the current activity enters the background. As a result, this method can’t do any heavy lifting, or it will invoke interface switching lag.

    The common usage scenario is the lightweight resource release when the interface enters the background.

    This state is best understood when another activity window pops up. Since there can only be one foreground activity, when the current interactive activity changes to another activity, the original activity must call onPause to enter ON_PAUSE state. But!!!!! It’s still visible, it’s just not interactive. It’s also a good place to appreciate the difference between foreground interactivity and visibility.

  • OnStop: called when the activity is not visible. After the call, the activity enters the ON_STOP state.

    Invisibility here is in the strict sense of invisibility.

    When the activity cannot interact, the onPause method is called back and the ON_PAUSE state is entered. However, if you enter another full-screen activity instead of a small window, when the new activity screen is displayed, the original activity will enter the ON_STOP state and the onStop method will be called. Also, when the activity is first created, the screen is displayed after the onResume method, so the onStop method is called back after the onResume method of the new activity is called back.

    Note that the started activity does not wait for onStop to finish executing before being displayed. Therefore, if the onStop method does some time-consuming operations, it will not cause the started activity to be delayed.

    The purpose of the onStop method is to release resources. Because it is called back after another activity is displayed, you can do some relatively heavy resource release operations, such as interrupting network requests, disconnecting from the database, releasing camera resources, and so on.

    If all activities in an application are in the ON_STOP state, the application is likely to be killed by the system. If an activity in the ON_STOP state is reclaimed by the system, the view information of the activity is saved into the bundle. The next time you resume the activity, you can restore it in onCreate or onRestoreInstanceState.

  • OnRestart: called when you cut back to the activity from another activity. The onStart method is called immediately after this method is called, and the activity enters the ON_START state.

    This method is typically called when an activity is restarted from the ON_STOP state. Immediately after executing this method, the onStart method is executed, and the Activity enters the ON_START state, bringing it to the foreground.

  • OnDestroy: This method is called back when the activity is killed by the system or after the Finish method is called. After calling this method, the activity enters the ON_DESTROY state.

    This method is the last method the activity calls back to before being destroyed. We need to free up all resources in this method to prevent memory leaks.

    The activity that is called back to this method is waiting to be reclaimed by the system. If you start the activity again, you need to execute it from onCreate to recreate the activity.

That concludes the seven most critical lifecycle methods. It should be noted that three dimensions are used to distinguish different types of states in the outline 1 figure, but it is obvious that the same type of state is not equivalent. For example, ON_START indicates that the activity is in the foreground, while ON_PAUSE indicates that the activity is in the background. This is probably why Google distinguishes the on_start and on_pause states, which are not consistent states.

These seven lifecycle callback methods are the most important and require a good understanding of the state transitions of the activity that each callback method is designed to perform. Once you understand state transitions, you can write stronger code.

Other lifecycle callback methods

  • onActivityResult

This method is also common and needs to be used in conjunction with startActivityForResult.

The scenario used is to start an activity and expect to return data when the activity ends.

When the started activity ends, return to the original activity, which will call back to the onActivityResult method. This method is executed before all other lifecycle methods. How onActivityResult is used won’t be covered here, we’ll focus on the life cycle.

  • onSaveInstanceState/onRestoreInstanceState

These two methods are mainly used to store and recover interface data in the event that an Activity is accidentally killed. What is accidental killing?

If you actively hit the back button, call the Finish method, clear the background app from the multitasking list, and so on, indicating that the user wants to exit the activity intact, there is no need to keep the interface data, so neither method is called. When the application is accidentally killed by the system, or the activity is destroyed due to a system configuration change, the user returns to the activity expecting the interface data to still be there. The onSaveInstanceState method is used to save the interface data. The onRestoreInstanceState method is called to restore the data while the activity is recreated and running. In fact, the parameters of the onRestoreInstanceState method are the same as those of the onCreate method, but the timing of their callbacks is different. Therefore, the key factor in determining whether to execute is whether the user expects the interface data to still exist when the activity is returned.

A few things to note here:

  1. The onSaveInstanceState method is called at different times in different Android versions. At present, the author’s source code is API30, which can be seen in the official comment:

    /*If called, this method will occur after {@link #onStop} for applications * targeting platforms starting with {@link android.os.Build.VERSION_CODES#P}. * For applications targeting earlier platform versions this method will occur * before {@link #onStop} and there are no guarantees about whether it will * occur before or after {@link #onPause}. */
    Copy the code

    In API28 and above onSaveInstanceState is called after onStop, but in lower versions it is called before onStop and the order between onPause and onStop is uncertain.

  2. The onSaveInstanceState method is called when the activity is in the background, rather than in exceptional cases. It is not certain that the activity will be killed while in the background, so it is safest to use the onSaveInstanceState method. Save the data first. OnRestoreInstanceState is called to restore data when it is actually killed due to an exception and the user expects the interface to recover the data. However, the onSaveInstanceState method is not called when an activity presses the return key or calls finish, because it is clear that the next time the user returns to the activity expects a new activity with a clean interface.

  3. OnSaveInstanceState cannot be a heavyweight data store. OnSaveInstanceState stores data by serializing data to the disk. If the stored data is too large, the interface will be stuck and frames will be dropped.

  4. Normally, each view overwrites these two methods. When the activity’s two methods are called, they delegate to the window to call the top-level viewGroup methods. And viewGroup recursive call of onSaveInstanceState/onRestoreInstanceState method view, so all the view of the state have been restored.

The interface data recovery is not discussed in detail here, interested readers can delve into it by themselves.

  • onPostCreate

This method is exactly the same as onPostResume, as is the onContextChange method. These three methods are not commonly used, but here I also point out one of them to talk about unified.

The onPostCreate method occurs after onRestoreInstanceState and before onResume, and it represents that the interface data has been fully restored, just short of being displayed for user interaction. These operations are not complete when the onStart method is called.

OnPostResume is the callback after the Resume method has been fully executed.

OnContentChange is the callback after setContentView.

These methods are not commonly used, only to understand. If you have a specific business need, you can use it.

  • onNewIntent

The scenario involved in this method is also repeated startup, but is different from the one in which the onRestart method is called.

We know that activities can be launched in multiple modes, among which singleInstance, singleTop, and singleTask all guarantee singleton state under certain circumstances. For singleTop, if we start an activity that is at the top of the stack and starts in singleTop mode, instead of creating an instance of the activity, it calls back the activity’s onNewIntent method. The method receives an intent parameter, which is the new launch intent instance.

Other cases, such as singleTask and singleInstance, call back to the onNewIntent method when such a forced singleton is encountered. We won’t expand on the boot mode here either, but I’ll probably write another article about it later.

Scenario lifecycle process

This section focuses on the sequence of callbacks to lifecycle methods in some scenarios. For an Activity, the above flow chart shows the sequence of lifecycle callbacks in various cases. However, when starting another activity, is onStop or the onStart being started first? These become more difficult to determine.

The best way to verify the order of life cycle callbacks is to write a demo, where the order of life cycle callbacks can be clearly observed by logging. Of course, view the source code is also a good method, but need to have a certain understanding of the system source code, we still choose a simple and crude method.

Normal start and end

onCreate -> onStart -> onResume -> onPause -> onStop -> onDestroy

The lifecycle of this case is easy to understand, with the normal start and end of an activity and no second activity involved. Finally, log printing:

The Activity to switch

Activity1:onPause Activity2:onCreate -> onStart -> onResume Activity1:onStop

When switching to another activity, the activity calls the onPause method to enter the background. The initiated activity calls three callback methods in sequence to prepare for interaction with the user. When the original activity calls the onStop method, it becomes invisible, and the last activity that was started is displayed.

There are only two points to remember to understand this lifecycle order: foreground and background, and visibility. After the onPause call, the activity goes into the background. Only one activity can interact with the foreground, so the original activity must enter the background before the target activity can start and enter the foreground. The activity becomes invisible after the onStop call, so the original activity calls the onStop method to go into the invisible state only when the target activity is about to interact with the user and needs to be displayed.

The process is similar when moving back from Activity2 to Activity1, except that Activity1 performs onRestart once before the rest of the lifecycle, similar to the previous process. Take a look at the log print below, which won’t be repeated here.

Let’s look at the life cycle log printing for switching to another activity:

Here we see the last callback to the onSaveInstanceState method, which we described earlier is called to save data when the activity goes into the background. It is not known whether the activity will be killed by the system in the background. Here’s another look at the life cycle log print when returned from Activity2:

Screen rotation

running -> onPause -> onStop -> onSaveInstanceState -> onDestroy

onCreate -> onStart -> onRestoreInstanceState -> onResume

When a resource configuration changes, the activity destroys and rebuilds, most commonly with screen rotation. At this point, the Activity that is an exception ends its life. Thus, onSaveInstanceState is called to save the data during destruction, and onRestoreInstanceState is called to restore the data when a new activity is recreated.

Take a look at log printing:

The background application is killed by the system

onDestroy

onCreate -> onStart -> onRestoreInstanceState -> onResume

This process is similar to the previous resource configuration changes, except that onSaveInstanceState is called back to save the data ahead of time when each activity is not visible, so there is no need to save the data again when it is killed by the background.

A startup with a return value

onActivityResult -> onRestart -> onResume

The focus here is on when the onActivityResult method of the original activity is executed when another activity is started using the startActivityForResult method and the activity is destroyed and returns. Most processes and activity switches are the same. But when the original Activity is returned, the onActivityResult method is executed before any other lifecycle methods. Take a look at log printing:

Repeated start

onPause -> onNewIntent -> onResume

This process is easy to overlook when studying the lifecycle. The previous introduction about onNewIntent has been mentioned, so I will not repeat it here. Remember that if the activity is currently at the top of the stack, onPause is called first and onNewIntent is called later. The design of the startup mode and return stack is not covered here, just remember the life cycle. Take a look at log printing:

Look at the lifecycle from the source code

So far we have covered some of the application knowledge of the lifecycle, this part is to delve into the source code to explore how the lifecycle is implemented in the source code. This will give you a deeper understanding of the life cycle and a better understanding of the source code design of the Android system.

Because there are so many lifecycle methods, it is impossible for me to go through them all; it would be too big and pointless. This part is divided into two parts: The first part is an overview of ActivityThread invocation methods for each lifecycle, so that you know how to find the appropriate source code to explore. The second part is to take the onResume method as an example and explain why the interface is still invisible when onResume is called at the first startup.

Look at the lifecycle from ActivityThread

As we all know, the startup of an Activity is coordinated by AMS. How is this coordinated?

Through the Handler mechanism article we know that Android program execution is to use the Handler mechanism to achieve message-driven. To control the Activity’s life cycle, AMS must continually send messages to the main thread; If the program wants to execute AMS commands, it must handle these message execution logic and cooperate with both ends to achieve such efficiency.

For example, if a leader wants to tell his subordinates to do work, he will definitely not give them the specific procedures of work, but just give them orders, such as: make a PPT for tomorrow’s speech, make me an appointment for next week’s flight and so on. Subordinates, then, must execute the specified logic according to these commands. So, in android applications, there must be a set of logic to execute “commands” from AMS separately. This is the set of handleXXX methods in ActivityThread. Give me a taste of what VS Code looks like:

Of course, applications receive management not only from AMS, but also from WMS, PMS, and other system services. System services run on system service processes and use Binder cross-process communication to send messages to applications when they need to control them. The application’s Binder threads send messages through handlers to the main thread for execution. As you can see, the main thread, binder threads, main thread handlers, and the ActivityThread class with the command execution logic written in advance must be initialized when the application is first created. Just say not to draw false explanation, draw a picture to feel:

Back to our life cycle theme. The execution methods of life cycle commands are as follows:

handleLaunchActivity;
handleStartActivity;
handleResumeActivity;
handlePauseActivity;
handleStopActivity;
handleDestroyActivity;
Copy the code

Of course there are more specific methods, just list some of the more common ones. These methods are in ActivityThread. There is only one ActivityThread per application, and it is the executor of the system service “command.”

Now that you know how AMS is deployed, how do you determine their execution sequence? Does AMS send handleStartActivity first or handleResumeActivity first? Here we need to have a certain awareness of the Activity start process, interested readers can click the Activity start process to learn, here will not expand.

Finally, can an ActivityThread decide to execute logic, regardless of AMS’s command? The answer is definitely no. You know, if you’re in a company and you don’t have the boss’s permission, can you use the company’s resources? Back on Android, the same is true. Applications cannot access system resources without AMS’s authorization, so AMS ensures that every application must conform to certain specifications. For those of you interested in this design, you can read the context Mechanism article to get a sense of it, to rethink the context.

Okay, a little digression, let’s get back to the point. In the following part, I will not expand to track the whole process, but locate the specific handle method to see what logic is implemented. Readers who are sensitive to the source code process can study it by themselves. The following focuses on the handleResumeActivity method.

Parse onRusume source code

Based on what we learned earlier, handleResumeActivity must be executed after handleLaunchActivity and handleStartActivity. Let’s look at the source code directly:

public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
        String reason) {...finalActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason); . ;if(! r.activity.mFinished && willBeVisible && r.activity.mDecor ! =null && !r.hideForNow) {
        ...
        if(r.activity.mVisibleFromClient) { r.activity.makeVisible(); }}... }Copy the code

I’ve captured two very important parts of the code. PerformResumeActivity eventually executes the onResume method; activity.makeVisible(); To actually make the interface appear on the screen, let’s take a look at makeVisible():

void makeVisible(a) {
    if(! mWindowAdded) { ViewManager wm = getWindowManager(); wm.addView(mDecor, getWindow().getAttributes()); mWindowAdded =true;
    }
    mDecor.setVisibility(View.VISIBLE);
}
Copy the code

If it has not been added to the screen, the windowManager addView method is called to add it, after which the Activity interface actually appears on the screen. In response to the previous question: why does popupWindow on onResume throw an exception but popupWindow on Dialog does not? The token is NULL exception will be raised if the popupWindow is attached to the parent interface. The Dialog is an application-level window and does not need to be attached to any window, so it is fine for the Dialog to pop up in the onCreate method. To verify our judgment, I print the windowToken of the decorView during its lifetime, and when the decorView is added to the screen, it is assigned the token.

As you can see, the interface does not appear on the screen until the onPostResume method is executed. The interface doesn’t actually appear on the screen until onWindowFocusChange is executed.

Ok, let’s go back to the original source code and dive into the performResumeActivity method to see where the onResume method is executed:

public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
        String reason) {...try{...if(r.pendingIntents ! =null) {
            // Determine whether the newIntent method needs to be executed
            deliverNewIntents(r, r.pendingIntents);
            r.pendingIntents = null;
        }
        if(r.pendingResults ! =null) {
            // Determine if the onActivityResult method needs to be executed
            deliverResults(r, r.pendingResults, reason);
            r.pendingResults = null;
        }
        // Callback the onResume method
        r.activity.performResume(r.startsNotResumed, reason);

        r.state = null;
        r.persistentState = null;
        // Set the state
        r.setState(ON_RESUME);

        reportTopResumedActivityChanged(r, r.isTopResumedActivity, "topWhenResuming"); }... }Copy the code

If onNewIntent or onActivityResult is not executed, then performResume is called.

final void performResume(boolean followedByPause, String reason) {
    dispatchActivityPreResumed();
    performRestart(true /* start */, reason); . mInstrumentation.callActivityOnResume(this); . onPostResume(); . }public void callActivityOnResume(Activity activity) {
    activity.mResumed = true; activity.onResume(); . }Copy the code

Again, just focus on the big picture. The performRestart method is called first. This method internally determines whether the onRestart and onStart methods need to be executed, which is mandatory if the activity is returning from another activity. Then use the onResume method of the Instrumentation to move the Activity back and forth. When the onResume callback is complete, the onPostResume() method is called again.

This concludes the handleResumeActivity method and gives you a better understanding of why the interface is not displayed when onResume or even onPostResume is called back. Specific code logic is very much, and about the life cycle of the code I just picked the key to say, other source code, interested readers can go to the source code. The author here is more to act as a result of a brick to attract jade. To learn from the source code to knowledge, you must read the source code manually, follow the article to read the fact that the harvest is not big.

View activities and their life cycle from system design

In the author’s opinion, every knowledge is designed by weighing various conditions in order to solve specific problems in specific scenarios. After learning each piece of knowledge, the author always likes to think about the underlying design idea of this piece of knowledge, what problems he needs to solve and what conditions he has weighed. Keep thinking to see each knowledge point from a higher perspective.

To understand the design of the lifecycle, you first need to understand the Activity itself. If there were no Activity, how would we write a program? Have you suddenly noticed that without an activity, our program has no place to start? The Activity class is a key component of an Android application, and the way activities are launched and combined is a fundamental part of the platform’s application model.

I believe many readers have written c language, Java or other languages of course design, our program entrance is the main function. Starting with the main function, depending on user input, you can enter different functional modules, such as the change information module, the view module, and so on. The application model which takes function module as the basic component is our original programming model. The Android application, we’ll say, has several interfaces. We are more concerned with jumping between interfaces than between functional modules. When we design our programs, we say what does this interface do, what does that interface do, how does the interfaces work together. For users, they perceive separate interfaces as well. When we call the email sending interface of the email app through the communication software, we like to see only the email sending interface, without seeing the inbox, login and registration interface. Function module as the application model of the design from a main function module entry, and then through the user input to call different function modules. Similarly, Android applications have a home screen that accepts user actions to call other screens. Composed of Android programs, is a interface, and each interface, corresponding to an Activity. Therefore, Activity is a fundamental component of the Application model for the Android platform.

The application model of the function module enters the main function module from the main method, while the Android application starts the “LaunchActivity” from the main method of ActivityThread and receives the AMS scheduling. This is the activity configured as main in AndroidManifest, which is the first activity to be opened when the application starts. So the first interface is opened, the other interface according to the user’s operation to jump in turn.

So how can each interface be decoupled from each other, their display is not chaotic, the interface between the orderly jump and so on? The authorities have done all this work for us. Activity is developed under this design idea. When we developed the Activity, we followed his design ideas. When we develop an app, the first thing we have to think about is how to design the interface. Once you’ve designed the interfaces, it’s time to think about how to develop each one. So how do we customize each interface? How to design the functions of each interface according to our requirements? The Activity does not have a main method. Where should our code be executed? The answer is: lifecycle callback methods.

Now, you can understand why starting an activity is not a simple new. An Activity has a lot of responsibilities and a lot of logic to initialize. When an Activity is started, it calls back and forth different lifecycle methods depending on how it is started. The onCreate method is responsible for initializing the entire interface and all the functional components. It’s kind of like the entry function for our function module, where we design the layout of our interface with setContentView, set the listener for each view with setOnClickListenner, etc. In MVVM design mode, you also need to initialize the viewModel, bind the data, and so on. This is the first very important aspect of the life cycle.

And when the interface display, exit, we need to apply for or release resources. As the camera example I mentioned above, I applied for the camera permission in wechat Scan. If resources are not released when ENTERING the background, the camera cannot be used when opening the system, and the resources are occupied. Therefore, another important role of the life cycle is to do a good job of allocating and releasing resources to avoid memory leaks.

Other life cycle functions, such as interface data recovery, interface switching logic processing, etc., will not be described, have been involved in the previous.

The focus of this section is to understand the point that An Android application model is based on Activity. The lifecycle becomes more aware when the interface is launched and switched from one interface to another.

The last

It’s impossible to cover the Activity life cycle in a single article. The more you study him, the more you get involved. Every knowledge point is like a melon on the vine, if simply pick a melon, that is a melon; If you grab the vine and pull it out, you’re gonna rip the whole shelf out. This article is also intended to provide readers with a way to think after the knowledge related to the life cycle.

Hope this article is helpful.

Full text here, the original is not easy, feel help can like collection comments forward. I have no talent, any ideas welcome to comment area exchange correction. If need to reprint please comment section or private communication.

And welcome to my blog: Portal