Deep understanding of Android Activity startup mode

Insert image description here

In Android application development, Activity is the core component of the user interface, and the startup mode of the Activity is the key factor that determines how the application interface interacts, manages, and is presented in the task stack. The correct choice of startup mode can optimize the user experience, improve application performance, and ensure that the application remains stable in various scenarios. This article will delve into the Activity startup mode in Android and explain in detail the purpose and applicable scenarios of each mode.

The importance of Activity startup mode

With the development of mobile applications, user experience has become increasingly important. Different application interfaces need to adapt to changing usage scenarios, which requires us to have a deep understanding of Activity startup mode. The startup mode determines how interfaces interact with each other, how Activity instances are created, managed, and destroyed, and how they are arranged in the task stack. Understanding the characteristics of different startup modes can help developers better control the application interface process, optimize memory usage, and improve user-perceived application speed.

Choose the startup mode that suits the scenario

Different application scenarios require different startup modes to achieve the best results. Android provides four basic startup modes, each with unique advantages. When choosing a launch mode, we need to consider the user's desired interface interactions, data sharing needs, and the overall architecture of the application.

Standard mode

Standard mode is the default startup mode, and a new instance is created every time the Activity is started. This mode is suitable for independent interfaces and does not require sharing of data. For example, for a simple calculator application, each time the calculator is launched, it should be a brand new instance.

SingleTop mode

The SingleTop pattern is suitable for interfaces that need to frequently update data or respond to new intents. For example, when a message notification interface receives a new message, it only needs to update the content of the existing interface without creating a new instance. Another example is a music player app where the user frequently switches songs but the interface remains the same.

SingleTask mode

The SingleTask mode is suitable for interfaces that serve as application entry points to ensure that only one instance exists. For example, the main interface of a calendar application should always be the same instance, and multiple interfaces will not be created when users view schedules at different times. In addition, only one instance of a single task stack exists, ensuring that users do not get lost in the task stack.

SingleInstance mode

SingleInstance mode is suitable for interfaces that need to be processed independently. For example, the social sharing function pops up a separate sharing interface after clicking the share button. After the user completes the sharing, he can directly return to the original application interface without being affected by other interfaces, providing a seamless user experience.

Sample code demonstration

Set activity startup mode

In the AndroidManifest.xml file, we can easily specify the startup mode of the Activity by setting the android:launchMode attribute as follows:

<activity
    android:name=".MainActivity"
    android:launchMode="singleTop">
</activity>
Handling SingleTop mode

In SingleTop mode, we can handle new intentions or update data by overriding the onNewIntent() method. The sample code is as follows:

public class MyActivity extends AppCompatActivity {
    
    
    // ...

    @Override
    protected void onNewIntent(Intent intent) {
    
    
        super.onNewIntent(intent);
        // 在这里处理新的意图或更新数据
    }
}
Handling SingleTask mode

In SingleTask mode, we also need to handle new intentions or update data in the onNewIntent() method. At the same time, we can also determine whether the Activity is restarted from the history stack by checking whether getIntent().getFlags() contains the Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY flag. The sample code is as follows:

public class MyActivity extends AppCompatActivity {
    
    
    // ...

    @Override
    protected void onNewIntent(Intent intent) {
    
    
        super.onNewIntent(intent);
        // 在这里处理新的意图或更新数据

        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
    
    
            // Activity 是从历史堆栈中重新启动的
        }
    }
}

Precautions for use

  • Avoid abusing the SingleInstance pattern: Although the SingleInstance pattern is useful when working on an interface independently, overuse can lead to cluttered task stacks and is not suitable for use in regular interfaces.
  • Note on life cycle in SingleTop mode: In SingleTop mode, when the Activity is on top of the stack, the instance is not recreated. Therefore, be careful with lifecycle methods such as onPause(), onResume(), etc. to ensure that the interface state is correct.
  • Reasonable use in SingleTask mode FLAG_ACTIVITY_CLEAR_TOP: If you use FLAG_ACTIVITY_CLEAR_TOP to start an Activity in SingleTask mode, all activities above the target Activity will be cleared. When you need to return to the specified interface, pay attention to the impact of this flag.
  • Consider the relationship between task stacks: Activities of different modes may exist in different task stacks. It is necessary to understand the relationship between task stacks and avoid confusion between interfaces.

task stack

The task stack is the mechanism used by the Android system to manage the hierarchy of the application interface. Each application has a task stack at runtime that stores its Activity instances.

The behavior of the task stack is closely related to the activity's startup mode. Different startup modes will affect how the activity is managed and interacted in the task stack.

Task stack life cycle

The life cycle of the task stack is related to the life cycle of the application. Activity instances in the task stack are managed accordingly as the application is started, paused, and closed.

  • Create task stack: When the application starts, the system will create a new task stack for the application and put the started Activity into it. The task stack is managed according to the Last-In-First-Out principle.
  • Activity addition and removal: When a new Activity is started, the system pushes it to the top of the task stack. When an activity completes its task or is closed, the system removes it from the task stack.
The role of the task stack

The task stack plays an important role in the switching and management of application interfaces, helping to maintain the status and user experience of the application.

  • Interface navigation: The task stack can record the user's navigation path between different interfaces in the application, so that the user can return to the previous interface through the return button.
  • State saving: The task stack can help save the state of the activity. When the user switches back to the application from the background, the previous interface state can be restored.
Manage activities in the task stack

Properly managing activities in the task stack can enhance user experience and optimize application performance.

  • Clear the task stack: By setting the android:clearTaskOnLaunch attribute, you can clear the task stack in the entry Activity of the application to ensure that the user enters the application every time A new task stack.
  • Switch task stack: Through the FLAG_ACTIVITY_NEW_TASK flag and different startup modes, the Activity can be started in different task stacks to implement different task stacks switch between.

in conclusion

In Android application development, reasonable selection of Activity startup mode can greatly affect the performance and user experience of the application. By in-depth understanding of the characteristics and applicable scenarios of each startup mode, developers can better plan the interface interaction of the application and achieve a high-quality and smooth user experience. In actual development, the appropriate startup mode can be flexibly selected according to application requirements to help build excellent Android applications.

Finally, we share a complete set of Android learning materials to give some help to those who want to learn Android!

Applies to:

  • Anyone who wants to learn Android development but doesn't know where to start
  • Also for anyone who's already started Android development but wants to get better at it

1. Learning routes in all directions of Android

Here is a general roadmap for you to become a better Android developer. Its usefulness is that you can find corresponding learning resources according to the above knowledge points to ensure that you learn more comprehensively. If the following learning route can help everyone become a better Android developer, then my mission will be accomplished:

Including: Android application development, system development, audio and video development, Flutter development, small program development, UI interface, vehicle system development, etc.

Insert image description here

2. Learning software

If a worker wants to do his job well, he must first sharpen his tools. Commonly used Android Studio video tutorials for learning Android and the latest Android Studio installation package are here, saving everyone a lot of time.


3. Advanced learning videos

When we are studying, the source code of books is often difficult to understand and difficult to read. At this time, video tutorials are very suitable. With vivid images and practical cases, it is scientific and interesting to learn more conveniently.

Insert image description here

4. Practical cases

Optical theory is useless. You must learn to follow along and practice it in order to apply what you have learned to practice. At this time, you can learn from some practical cases.

Insert image description here

5. Reading classic books

Reading classic Android books can help readers improve their technical level, broaden their horizons, master core technologies, and improve their ability to solve problems. At the same time, they can also learn from the experiences of others. For readers who want to learn Android development in depth, reading classic Android books is very necessary.

Insert image description here

6. Interview materials

We must learn Android to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and Alibaba bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.

图片

Please add image description

This complete version of the complete set of Android learning materials has been uploaded to CSDN. If you need it, friends can scan the CSDN official certification QR code below on WeChat to get it for free [保证100%免费]

Guess you like

Origin blog.csdn.net/Android23333/article/details/134869983