Android: Illustration of four startup modes and explanation of actual application scenarios

A project will include multiple activities. The system uses the task stack to store the created Activity instance. The task stack is a "last in first out" stack structure. For example, if we start the same Activity multiple times. The system will create multiple instances and put them in the task stack in turn. When you press the back key to return, each time you press it, an Activity pops out of the stack until the stack is empty. When there is no Activity in the stack. The system will recycle the task stack.

The Activity in the above example does not have a startup mode set, and you will find that the same Activity is started multiple times. However, the system has created multiple instances, wasting memory in vain, and Android has already considered this situation for us. Android provides 4 startup modes for the creation of Activity, depending on the actual application scenario. Selecting different startup modes for Activity minimizes the pressure of creating a new Activity in the stack every time, and reduces memory usage.

What are the specific instructions and usage scenarios for the startup mode? The following is based on this blog post to clarify the doubts one by one.

1. Detailed explanation of Android boot mode

]![Write picture description here

1. Standard Standard Mode

Description: The default mode when Android creates an Activity. If no startup mode is set for the Activity, it defaults to the standard mode. Every time an Activity is started, a new instance is created and pushed onto the stack, regardless of whether the instance exists or not.

 

Life cycle: As you can see above, the life cycle of each instance Activity that is created conforms to the typical situation, and its onCreate, onStart, and onResume will be called.

Example: At this time, there are three activities A, B, and C in the Activity stack. At this time, C is at the top of the stack, and the startup mode is Standard mode .

If you add a click event to C Activity, you need to jump to another C Activity of the same type. The result is that another C Activity enters the stack and becomes the top of the stack.
Write picture description here

2. SingleTop stack top multiplexing mode

Description: There are two processing situations: when the Activity to be created is already at the top of the stack, the Activity at the top of the stack will be directly reused at this time. No new Activity will be created; if the Activity to be created is not at the top of the stack, a new Activity will be created and pushed into the stack again, the same as the Standard mode.

Life cycle: If the Activity at the top of the stack in case 1 is directly reused, its onCreate and onStart will not be called by the system because it has not changed. But a new method onNewIntent will be called back (this method will not be called back when the Activity is created normally).

For example: At this time, there are three activities A, B, and C in the Activity stack. At this time, C is at the top of the stack, and the startup mode is SingleTop mode . Case 1: To add a click event in C Activity, you need to jump to another C Activity of the same type.

The result is a direct reuse of the C Activity at the top of the stack.

Case 2: To add a click event in C Activity, you need to jump to another A Activity. The result is to create a new Activity on the stack. become the top of the stack.


Write picture description here

3. SingleTask stack multiplexing mode

Note: If the Activity to be created is already in the stack, a new Activity will not be created at this time, but all other Activity above the Activity in the stack will be destroyed, making it the top of the stack.

Lifecycle: Same as in SingleTop mode. It will only call back the onNewIntent method in the Activity again

Example: At this time, there are three Activities A, B, and C in the Activity stack. At this time, C is at the top of the stack, and the startup mode is SingleTask mode .

Case 1: To add a click event in C Activity, you need to jump to another C Activity of the same type. The result is to use the C Activity at the top of the stack directly. Case 2: To add a click event in C Activity, you need to jump to another A Activity.

The result is that all B and C above A Activity are destroyed, making A Activity the top of the stack.
Write picture description here

4. SingleInstance single instance mode

Description: SingleInstance is special, it is a global singleton mode and an enhanced SingleTask mode. In addition to all its features, it is enhanced by one point: Activity with this mode can only be located in a task stack alone.

This application that is often used in the system, such as Launch, the application of the lock screen key, etc., is only one in the entire system! So it is generally not used in our application. Just understand.

Example: For example, A Activity is this mode, after A is started. The system will create a separate task stack for it, due to the nature of multiplexing within the stack. A possible request will not create a new Activity unless this unique task stack is destroyed by the system.

2. How to use the startup mode

1. Specify the Activity startup mode in Manifest.xml

A static specifying method, specifying its startup mode when declaring the Activity in the Manifest.xml file, so that the Activity will be created according to the specified mode when jumping in the code. Examples are as follows:

        <activity android:name="..activity.MultiportActivity" android:launchMode="singleTask"/>

2. When starting the Activity. Specify the startup mode in the Intent to create an Activity

A dynamic startup mode. After a new Intent is created, a startup mode is dynamically specified through the addFlags method of the Intent. Examples are as follows:

        Intent intent = new Intent();
        intent.setClass(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);

Note: Both of the above two methods can specify the startup mode for the Activity, but there are still differences between the two.

 

(1) Priority : The dynamic designation method means that the other method has a higher priority than the first one . If the two exist at the same time, the other method shall prevail.


(2) Limited scope : The first method cannot directly specify the FLAG_ACTIVITY_CLEAR_TOP flag for the Activity , and the other method cannot specify the singleInstance mode for the Activity.

 

3. Activity Flags

The flag bit can not only set the startup mode of the Activity, as described above, dynamically specify the startup mode, such as FLAG_ACTIVITY_NEW_TASK and FLAG_ACTIVITY_SINGLE_TOP . It can also affect the running state of Activity, such as FLAG_ACTIVITY_CLEAN_TOP and FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS and so on.

The following introduces a few basic flag bits. Don't memorize them, just understand a few, and check the official documentation when necessary.

1. FLAG_ACTIVITY_NEW_TASK

The role is to specify the " SingleTask " startup mode for the Activity. It has the same effect as specifying in AndroidMainfest.xml.

2. FLAG_ACTIVITY_SINGLE_TOP

The role is to specify the " SingleTop " startup mode for the Activity, which is the same as specifying the effect in AndroidMainfest.xml.

3. FLAG_ACTIVITY_CLEAN_TOP

An activity with this flag bit will pop other activities in the same task stack as the activity when it starts. Usually appears with the SingleTask startup mode. It will finish the role of SingleTask. But in fact, the SingleTask startup mode has the function of this flag bit by default

4.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS

Activities with this flag will not appear in the list of historical activities. Usage scenarios: In some cases, when we do not want the user to return to the Activity through the history list, this flag reflects its effect. It is equivalent to specifying the properties of the Activity in xml:

android:excludeFromRecents="trure"

4. Actual application scenarios of startup mode

The Standard mode among the four modes is the most common one, and there is nothing special to pay attention to. The SingleInstance mode is the singleton mode of the entire system, which is generally not applied in our applications. Therefore, here is a detailed explanation of the application scenarios of SingleTop and SingleTask modes:

1. Application scenarios of SingleTask mode

The most common application scenario is to keep our application open with only one instance of Activity. The most typical example is the home page (Home page) displayed in the application.

Suppose the user jumps to other pages on the home page, and wants to return to the home page after running multiple operations. If the SingleTask mode is not used, the home page will be seen many times during the process of clicking return, which is obviously an unreasonable design.

 

2. Application scenarios of SingleTop mode

Suppose you want to start an activity of the same type in the current activity, it is recommended to specify the startup mode of this type of activity as SingleTop, which can reduce the creation of activities and save memory!

 

3. Note: Lifecycle callbacks when reusing Activity

It is also necessary to consider the problem of carrying page parameters when an Activity jumps .

Because when an Activity is set to SingleTop or SingleTask mode, when jumping to this Activity and reusing the original Activity , the onCreate method of this Activity will not run again. The onCreate method will only be run when the Activity is first created.

In general, the data initialization and UI initialization of the page will be performed in the onCreate method. Assuming that the display data of the page has nothing to do with the parameters passed by the page jump, there is no need to worry about this problem. If the data displayed on the page is obtained through the getInten() method, Then the problem will arise: getInten() always obtains the old data, and cannot receive the new data transmitted during the jump!

Here is an example to explain:

Manifest.xml
        <activity
            android:name=".activity.CourseDetailActivity"
            android:launchMode="singleTop"
            android:screenOrientation="portrait" />
public class CourseDetailActivity extends BaseActivity{
  ......
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_detail_layout);
        initData();
        initView();
    }

   //初始化数据
    private void initData() {
        Intent intent = getIntent();
        mCourseID = intent.getStringExtra(COURSE_ID);
    }

    //初始化UI
    private void initView() {
    ......
    }
    ......
}

The CourseDetailActivity in the above code sets the startup mode to SingleTop mode in the configuration file. According to the introduction of the startup mode above, it can be known that when CourseDetailActivity is at the top of the stack. When jumping the page to CourseDetailActivity again, the original Activity will be reused directly, and the data to be displayed on this page is obtained from the getIntent() method, but the initData() method will not be called again, and the page cannot display new The data.

 

Of course, the system has already thought about such a situation for us. At this time, we need another callback onNewIntent (Intent intent) method . This method will pass in the latest intent, so we can solve the above problem. The suggested approach here is to go to setIntent again. Then again to initialize the data and UI. Code example as seen below:

/*
* 复用Activity时的生命周期回调
*/
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        initData();
        initView();
    }

In this way, you can jump repeatedly and display different content in a page.

 

The startup mode is actually a knowledge point that you will learn when you first learn Android. It used to be half-understood. Some knowledge points are actually the same as the design mode. You don't use it but just learn it. Going to use will make these your own. Part of the article refers to "Android Development Art Exploration". Recommended books.

 

I have been using the startup mode recently, so here is a brief summary. There are many articles about this on the Internet, but many summaries are intentionally harmless.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325812201&siteId=291194637