[Android] Active startup mode

Source: Internet
Author: User

There are four startup modes, Standard, Singletop, Singletask, and singleinstance, which can be specified in androidmanifest.xml by assigning Android:launchmode property to select the startup mode. In the actual project we should specify the appropriate startup mode for each activity according to the specific requirements.

1. Standard

Standard is the active default startup mode, which is automatically used by all activities without explicit designation. As a result, all the activities we have written so far have been used in standard mode. After learning, we already know that Android is using the activity stack to manage activities, in standard mode (that is, by default), whenever a new activity is started, it will be in the active stack in the stack, and at the top of the stack position. For activities that use standard mode, the system does not care if the activity is already present in the active stack, and a new instance of the activity is created each time it is started. We now experience the standard mode through practice, and this time we are going to modify the Activitytest project and open the Activitytest project.

Modify the code for the OnCreate () method in Firstactivity as follows:

@Overrideprotected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); LOG.D ("Firstactivity", This. toString ());    Requestwindowfeature (Window.feature_no_title);    Setcontentview (r.layout.first_layout);    Button button1 = (button) Findviewbyid (r.id.button_1); Button1.setonclicklistener (NewOnclicklistener () {@Override         Public void OnClick(View v) {Intent Intent =NewIntent (firstactivity. This, Firstactivity.class);        StartActivity (Intent); }    });}

The code looks strange, starting firstactivity on the basis of firstactivity. Logically this really doesn't make sense, but our focus is on the standard mode, so don't worry about what the code is really used for. We also added a line of print information to the OnCreate () method to print the currently active instance.

Now re-run the program, and then click on the Firstactivity interface two times a row of buttons, you can see the LogCat print information.

From the printed information we can see that each click of the button will create a new firstactivity instance. There will also be three instances of firstactivity in the return stack, so you need to double-press the back key three times to exit the program.

The principle of standard mode, as shown in:

2. Singletop

In some cases, you may find the standard mode less reasonable. Activity is already at the top of the stack, why start again when you want to create a new activity instance? Don't worry, this is just a system default startup mode, you can completely adapt to your own needs, such as the use of Singletop mode. When the active startup mode is specified as Singletop, if it is found that the stack top of the active stack is already active at the start of the activity, it is considered that it can be used directly and no new activity instances will be created. In practice, let's try to modify the startup mode of firstactivity in Androidmanifest.xml as follows:

<activityandroid:name=". Firstactivity "android:launchmode=" Singletop "android:label=" This is Firstactivity " >                <intent-filter>        <action android:name="Android.intent.action.MAIN" />        <category android:name="Android.intent.category.LAUNCHER" />    </intent-filter></activity>

Then rerun the program and view LogCat to see that an instance of Firstactivity has been created, as shown in:

But then no matter how many times you click the button will not have new printing information appear, because the current firstactivity is already on the top of the stack back, whenever you want to start a firstactivity will be directly using the top of the activity, so firstactivity There will only be one instance, and you can exit the program by pressing the back key only once. However, when the firstactivity is not at the top of the stack, then the firstactivity is started and a new instance is created. Let's experiment with modifying the code of the OnCreate () method in Firstactivity as follows:

@Overrideprotected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); LOG.D ("Firstactivity", This. toString ());    Requestwindowfeature (Window.feature_no_title);    Setcontentview (r.layout.first_layout);    Button button1 = (button) Findviewbyid (r.id.button_1); Button1.setonclicklistener (NewOnclicklistener () {@Override         Public void OnClick(View v) {Intent Intent =NewIntent (firstactivity. This, Secondactivity.class);        StartActivity (Intent); }    });}

This time we clicked the button and started the secondactivity. Then modify the code for the OnCreate () method in Secondactivity, as follows:

protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); LOG.D ("Secondactivity", This. toString ());    Requestwindowfeature (Window.feature_no_title);    Setcontentview (r.layout.second_layout);    Button button2 = (button) Findviewbyid (r.id.button_2); Button2.setonclicklistener (NewOnclicklistener () {@Override         Public void OnClick(View v) {Intent Intent =NewIntent (secondactivity. This, Firstactivity.class);        StartActivity (Intent); }    });}

We added the code to launch Firstactivity in the button click event in Secondactivity. Now rerun the program, click the button in the Firstactivity interface to enter the Secondactivity, and then click on the Secondactivity interface button, will re-enter to Firstactivity.
View the print information in the LogCat as shown in:

You can see that the system has created two different firstactivity instances, because the top of the stack activity has become secondactivity when Firstactivity is started again in secondactivity, and therefore creates a new Firstactivity instance. Pressing the back key now returns to Secondactivity, pressing the back key again to return to Firstactivity, and then pressing the return key again to exit the program. The principle of the Singletop mode, as shown in:

3. Singletask

Using the Singletop mode is a good way to solve the problem of repeatedly creating top-of-stack activities, but as you can see earlier, if the activity is not at the top of the stack, it is possible to create multiple active instances. So is there a way to get an activity that only has one instance in the context of the entire application? This is accomplished with the help of the Singletask model. When the active startup mode is specified as Singletask, each time the activity is started, the system first checks the activity stack for the existence of an instance of the activity, uses the instance directly if found to exist, and puts all the activities on top of the activity out of the stack, creating a new activity instance if no discovery is made.

We can still use the code to understand it more intuitively. To modify the startup mode of firstactivity in Androidmanifest.xml:

<activityandroid:name=". Firstactivity "android:launchmode=" Singletask "android:label=" This is Firstactivity " >                <intent-filter>        <action android:name="Android.intent.action.MAIN" />        <category android:name="Android.intent.category.LAUNCHER" />    </intent-filter></activity>

Then add the Onrestart () method to the Firstactivity and print the log:

@OverrideprotectedvoidonRestart() {    super.onRestart();    Log.d("FirstActivity""onRestart");}

Finally, add the OnDestroy () method to the Secondactivity and print the log:

@OverrideprotectedvoidonDestroy() {    super.onDestroy();    Log.d("SecondActivity""onDestroy");}

Now rerun the program, click the button in the Firstactivity interface to enter the Secondactivity, and then click on the Secondactivity interface button, will re-enter to Firstactivity.

View the print information in the LogCat as shown in:

In fact, from the printing information can be clearly seen in the secondactivity start firstactivity, you will find that the activity stack already exists a firstactivity instance, and is under the secondactivity, So secondactivity will stack from the activity stack, and firstactivity is back on top of the stack, so Firstactivity's Onrestart () method and Secondactivity OnDestroy () Method will be executed. Now there should be only one instance of firstactivity in the activity stack, click the back key to exit the program.

The principle of the Singletask mode, as shown in:

4. SingleInstance

The singleinstance mode should be the most special and complex of the four startup modes, and you need to take a bit more effort to understand the pattern. Unlike the above three startup modes, activities designated as SingleInstance mode enable a new activity stack to manage this activity (in fact, if the Singletask mode specifies a different taskaffinity, a new activity stack is also started). So what's the point of doing that? Imagine the following scenario, assuming that there is an activity in our program that allows other programs to invoke, how should we implement other programs and our programs to share an instance of the activity? Using the previous three startup modes is definitely not going to work because each application will have its own activity stack, and a new instance must be created when the same activity is stacked on a different activity stack. Using the SingleInstance mode can solve this problem, in this mode there will be a separate activity stack to manage the activity, regardless of which application to access the activity, the same activity stack shared, also solves the problem of shared activity instances.

The startup mode of secondactivity in XML:

<activityandroid:name=". Secondactivity "android:launchmode=" SingleInstance " >            <intent-filter>        <action android:name="Com.example.activitytest.ACTION_START" />        <category android:name="Android.intent.category.DEFAULT" />        <category android:name="Com.example.activitytest.MY_CATEGORY" />    </intent-filter></activity>

We will first specify the Secondactivity startup mode as singleinstance and then modify the code of the OnCreate () method in firstactivity:

@Overrideprotected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); LOG.D ("Firstactivity","Task ID is"+ GetTaskID ());    Requestwindowfeature (Window.feature_no_title);    Setcontentview (r.layout.first_layout);    Button button1 = (button) Findviewbyid (r.id.button_1); Button1.setonclicklistener (NewOnclicklistener () {@Override         Public void OnClick(View v) {Intent Intent =NewIntent (firstactivity. This, Secondactivity.class);        StartActivity (Intent); }    });}

The ID of the current return stack is printed in the OnCreate () method. Then modify the code for the OnCreate () method in secondactivity:

@Overrideprotected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); LOG.D ("Secondactivity","Task ID is"+ GetTaskID ());    Requestwindowfeature (Window.feature_no_title);    Setcontentview (r.layout.second_layout);    Button button2 = (button) Findviewbyid (r.id.button_2); Button2.setonclicklistener (NewOnclicklistener () {@Override         Public void OnClick(View v) {Intent Intent =NewIntent (secondactivity. This, Thirdactivity.class);        StartActivity (Intent); }    });}

It also prints the ID of the current return stack in the OnCreate () method, and then modifies the code of the button click event to start the thirdactivity. Finally, modify the code for the OnCreate () method in thirdactivity:

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    Log.d("ThirdActivity""Task id is " + getTaskId());    requestWindowFeature(Window.FEATURE_NO_TITLE);    setContentView(R.layout.third_layout);}

The ID of the current return stack is still printed in the OnCreate () method. Now rerun the program, click on the Firstactivity interface button to enter the Secondactivity, and then click on the Secondactivity interface button to enter the Thirdactivity.
View the print information in the LogCat as shown in:

As you can see, the secondactivity Task ID is different from firstactivity and thirdactivity, which means that secondactivity is actually stored in a separate activity stack, and only secondactiv in this stack ity this one activity. Then we press the Back button to return, you will find that thirdactivity unexpectedly directly returned to the firstactivity, and then press the Back button will return to Secondactivity, and then press the Next button to quit the program, this is why? In fact, the principle is very simple, because firstactivity and thirdactivity are stored in the same activity stack, when in
Thirdactivity interface Press the Back button, Thirdactivity will be out of the activity stack, then firstactivity becomes the top of the stack activity displayed on the interface, so there is a direct return from the thirdactivity back Firstactivity the situation. Then in the Firstactivity interface again press the back key, when the current activity stack is empty, so it shows another activity stack top activity, that is, secondactivity. Finally press the back key again, when all the activity stack is empty, also naturally quit the program.

The principle of the singleinstance mode, as shown in:

[Android] Active startup mode

Related Article

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.