Android: Illustration of four startup modes and actual application scenarios

Source: Internet
Author: User

Multiple activities are included in a project, and the task stack is used to store the created activity instances, which is a "LIFO" stack structure. Give me a chestnut, if we start the same activity many times. The system creates multiple instances and then puts them into the task stack. When you press the back key to return, each time an activity is pushed out of the stack until the stack is empty. There is no activity in the stack, no matter what. The task stack is reclaimed by the system.

The activity in the example above does not have a boot mode set, and you will find that you start the same activity multiple times. But the system has created many instances, wasted memory, so the situation of Android has long been for us to consider. Android provides 4 startup modes for activity creation, depending on the actual application scenario. Selecting different startup modes for activity minimizes the need to create a new activity in the stack each time, reducing memory usage.

Specific instructions and usage scenarios for the startup mode? The following is a blog of this article.

I. Android boot mode specific explanation

1. Standard mode

Description: The default mode when Android creates activity, assuming that no startup mode is set for activity, it defaults to the standard mode. Each time you start an activity, you create a new instance into the stack again, regardless of whether the instance exists.

life cycle: as seen above, the life cycle of each instance created is typical, and its oncreate, OnStart, and Onresume are called.

Example: at this time in the activity stack with a, B, c three activity, at this time C is at the top of the stack, the boot mode is standard mode .

If you add a click event to C activity, you need to jump to the same type of C activity. As a result, there is a C activity that goes into the stack and becomes the top of the stack.

2. singletop Stack top multiplexing mode

Note: There are two kinds of processing: the activity that needs to be created is already at the top of the stack, and the activity at the top of the stack is directly reused. No new activity is created, and if the activity that needs to be created is not on top of the stack, a new activity stack is created again, as in standard mode.

life cycle: If the activity at the top of the stack is directly reused, its oncreate, OnStart will not be called by the system, as it does not change. However, a new method Onnewintent will be called back (this method will not be recalled when activity is created normally).

Example: at this time in the activity stack with a, B, c three activity, at this time C is at the top of the stack, the boot mode is singletop mode . Scenario One: Adding a click event to C activity requires jumping to a similar type of C activity.

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

Scenario Two: Adding a click event to C activity, you need to jump to a activity. The result is creating a new activity into the stack. Become the top of the stack.


3. singletask Stack internal multiplexing mode

Note: If the activity that needs to be created is already in the stack, no new activity is created at this time, but the other activity above the activity that exists on the stack is destroyed to make it the top of the stack.

life cycle: same as in singletop mode. Just once again, callback the onnewintent method in the activity

Example: at this time the activity stack has a, B, c three activity. C is at the top of the stack and the boot mode is singletask mode .

Scenario One: Adding a click event to C activity requires jumping to a similar type of C activity. The result is a direct C Activity with the top of the stack. Scenario Two: Adding a click event to C activity, you need to jump to a activity.

The result is a activity above the B, c all destroyed, so that a activity becomes the top of the stack.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvsvrlcm1lbmc=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast "alt=" here to write a picture descriptive narrative "title=" ">

4. SingleInstance Single Instance mode

Description: SingleInstance is special, is a global singleton mode, is a strengthened singletask mode. In addition to having all of its features, it reinforces the point that an activity with this pattern can only be on a single task stack.

This is often used in the system of applications, such as launch, lock screen key applications, etc., the entire system only one! Therefore, it is not commonly used in our applications. To understand it.

Example: A activity is the pattern that starts after a. The system creates a separate task stack for it, due to the characteristics of the reuse of the stack. A request will not create a new activity unless the unique task stack is destroyed by the system.

two. How to use the startup mode 1. Specify activity startup mode in Manifest.xml

A statically specified method that specifies the startup mode of the activity at the same time in the Manifest.xml file, so that the activity is created according to the specified pattern when jumping in the code. Examples include the following:

        <activity android:name="..activity.MultiportActivity" android:launchMode="singleTask"/>
2. When the activity is started. Specify the startup mode in intent to create activity

A dynamic startup mode that, after new intent, dynamically specifies a startup mode by means of the intent Addflags method. Examples include the following:

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

Note: both of these methods can specify the startup mode for the activity, but they are still different.

(1) Priority : Dynamic designation means that the other one is higher than the first priority, if both exist at the same time, whichever is the other.


(2) Limited scope : The first method cannot specify the flag_activity_clear_top identifier directly for the activity, and the other way cannot specify singleinstance mode.

three. The Flags of the Activity

The marker bit can set the activation 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 operational state of the ACTIVITY, such as flag_activity_clean_top and flag_activity_exclude_from_recents .

Here are a few basic tags, do not rote, understand a few can be, when necessary to check the official documents.

1. Flag_activity_new_task

The function is to specify the "singletask" startup mode for the activity. Follow the androidmainfest.xml to specify the same effect.

2. Flag_activity_single_top

The function is to specify the "singletop" startup mode for the activity, as specified in the Androidmainfest.xml effect.

3. Flag_activity_clean_top

Activity with this tag bit will be launched with other activity on the same task stack. Typically appears with the Singletask startup mode. It will be finished Singletask function. In fact, the Singletask startup mode has the effect of this tag bit by default

4.flag_activity_exclude_from_recents

Activity with this tag bit does not show up in the list of today's historical activity, using the scenario: when we don't want the user to return to the activity through the history list, this marker bit reflects its effect. It is equivalent to specifying the properties of the activity in XML:

android:excludeFromRecents="trure"
Four. Actual application scenarios for startup mode

The standard mode in these four modes is the most common one, with little special attention. The singleinstance mode is a singleton mode of the whole system, which is not normally applied in our application. So, here is a detailed explanation of the use of singletop and singletask patterns:

1. Application Scenarios for Singletask mode

The most common scenario is to keep our app open and only have an activity instance. The most typical example is the home page shown in the app.

Assuming that the user jumps to another page on the page, runs multiple operations and wants to go back to the home page, assuming that you don't use the Singletask mode, you'll see the page more than once in the process of clicking back, which is obviously an unreasonable design.

2. Application Scenarios for Singletop mode

Assuming that you start the same type of activity in your current activity, it is recommended that the startup mode of this type of activity be specified as Singletop, which reduces activity creation and saves memory!

3. Note: Life cycle callbacks when reusing activity

There is also a question to consider when an activity jumps to carry the page number .

Since when a singletop or Singletask mode is set for an activity, it is possible to jump to a situation where the activity is re-used. The OnCreate method for this activity will not run again. The OnCreate method is only run the first time the activity is created.

The general OnCreate method will be the data initialization of the page, UI initialization, assuming that the page display data regardless of the page jump to pass the number of parameters, you do not have to worry about this issue, if the page display data is obtained through the Getinten () method, then the problem will appear: Getinten () Always get the old data, can not receive the jump when the new data sent!

The following, through a sample to explain specifically:

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 (); }//Initialize data    Private void InitData() {Intent Intent = getintent ();    Mcourseid = Intent.getstringextra (course_id); }//Initialize UI    Private void Initview() {    ......    } ......}

Coursedetailactivity in the above code in the configuration file set the startup mode is singletop mode, according to the introduction of the above boot mode can be learned, when the coursedetailactivity at the top of the stack. Jump to the page again to Coursedetailactivity will be directly re-use of the original activity, and this page needs to show the data is from the Getintent () method, but the InitData () method will not be called again, the page will not be able to display the new data.

Of course, the system has long thought for us, and then we need another callback Onnewintent (Intent Intent) method . This method will pass in the latest intent so that we can resolve the above problem. The proposed method here is to setintent again. And then again to initialize the data and UI. The code looks like the following:

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

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

Startup mode is actually a beginner Android will learn the knowledge point, once is also a know half understand, some knowledge point in fact with the design pattern, you do not use and just is learning is not able to grasp the essence, only really to use will these become your own, the article part of the content of the " Explore the art of Android development. Good book recommendation.

Recently in the use of startup mode, I would like to summarize a little, online about this kind of article also has a lot, but more summary summary or intentionally harmless.

Welcome to the wrong point ~
Hope to be of help to you:)

Android: Illustration of four startup modes and actual application scenarios

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.