Android Activity Series Summary (iii)--activity four types of startup modes

Source: Internet
Author: User

Introduction of Return Stack

A task is a series of activities that interact with the user when a particular job is executed. The Activity is arranged on the stack (that is, the return stack, also called the task stack) in its own order of opening.

First introduce the task stack:

(1) When the program opens, a task stack is created to store the activity of the current program, and all activity belongs to a task stack.
(2) A task stack contains a collection of activity, which is ordered to select which activity interacts with the user: only the activity at the top of the task stack can interact with the user.
(3) The task stack can be moved to the background and retains the status of each activity. And the user is ordered to list their tasks, and they do not lose their status information.
(4) When exiting the application: when all the activity in the task stack is purged from the stack, the task stack is destroyed and the program exits.

, is a simple example of a task stack:

Figure 1. Shows how each new Activity in the task adds items to the return stack. When the user presses the back button, the current activity is destroyed and the previous activity resumes execution.

Disadvantages of the task stack:
(1) Each time the page is opened in the task stack to add an activity, and only the task stack of activity all clear out of the stack, the task stack is destroyed, the program will exit, so that the use, the user experience is poor, you need to click Multiple return to the program to quit.
(2) Each time a page is opened, adding an activity to the task stack can also result in data redundancy, too much data duplication, and a memory overflow problem (OOM).

In order to solve the disadvantage of the task stack, we introduced the boot mode.

Second, the starting mode

Startup mode (Launchmode) plays an important role in the process of multiple activity jumps, and it can decide whether to generate new activity instances, reuse existing activity instances, and share a task with other activity instances. Here is a brief introduction to the concept of a task, which is an object with a stack structure, a task that can manage multiple activity, launch an application, and create a corresponding task.

The activity has the following four kinds of Launchmode:

    • Standard
    • Singletop
    • Singletask
    • SingleInstance

How do I configure the activity's startup mode?

The startup mode allows you to define how new instances of Activity are associated with the current task. You can define different startup modes in two ways:

    • Working with manifest files

      When you declare an activity in a manifest file, you can specify how the activity should be associated with the task at startup.

    • Using the Intent flag

      startActivity()when called, you can Intent include a flag in to declare how the new Activity (or whether) is associated with the current task.

Note: There are two ways of prioritizing: the priority defined in Intent is higher than the one defined in the manifest file.

Some startup modes that apply to manifest files cannot be used as Intent flags, and some startup modes that can be used as Intent flags cannot be defined in the manifest file.

Here are a few of the four startup modes and their application scenarios:

1. Standard

Standard mode is the default startup mode, which is not required to configure the Android:launchmode property, and you can also specify a value of.

Activity_main.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= " Http://schemas.android.com/apk/res/android "xmlns:tools=" Http://schemas.android.com/tools "android:layout_width= "Match_parent" android:layout_height= "match_parent" android:orientation= "vertical" android:paddingbottom= "@dimen/ Activity_vertical_margin "android:paddingleft=" @dimen/activity_horizontal_margin "android:paddingright=" @dimen/ Activity_horizontal_margin "android:paddingtop=" @dimen/activity_vertical_margin "tools:context=" Com.geniusvjr.standard_demo. Mainactivity "> <textview android:id=" @+id/tv "android:layout_width=" Match_parent "Android:la         yout_height= "Wrap_content"/> <button android:id= "@+id/btn_skip" android:layout_width= "Match_parent" android:layout_height= "Wrap_content" android:text= "Jump to Mainactivity"/></LINEARLAYOUT> 

Mainactivity.java

public class Mainactivity extends Appcompatactivity {    @Override    protected void OnCreate (Bundle Savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);        TextView TextView = (TextView) Findviewbyid (r.id.tv);        Textview.settext (This.tostring ());        Button button = (button) Findviewbyid (r.id.btn_skip);        Button.setonclicklistener (New View.onclicklistener () {            @Override public            void OnClick (View v) {                Intent Intent = new Intent (mainactivity.this, mainactivity.class);                StartActivity (intent);}}        );}    }

The TextView in the Mainactivity interface is used to display the serial number of the current activity instance, and the button is used to jump to the next firstactivity interface.
Then we click the button a few times, there will be the following phenomenon:

Are examples of mainactivity, but the serial numbers are different.
The principle of Stardard mode is as follows:

, each jump system generates a new Mainactivity instance in the task and is placed at the top of the stack structure, and when we press the back key, we can see the original mainactivity instance.
This is the standard startup mode, which generates a new instance, regardless of whether there are any existing instances.

2, Singletop

We android:launchmode= "Singletop" on the above basis for the specified attribute, and the system will handle the jump behavior according to the Singletop startup mode. We repeat the above several actions, will appear the following phenomenon:

We see this result is different from standard, three serial numbers are the same, that is, using the same mainactivity instance; If you press the back key, the program exits immediately, indicating that there is only one activity instance in the current stack structure. The principle of Singletop mode is as follows:

As shown, the system will first look in the stack structure to see if there is a mainactivity instance on the top of the stack, and if there is no new one, use it directly. Perhaps friends will have doubts, I only see the stack only one activity, if it is a number of activity what to do, if not at the top of the stack? We will then pass an example to confirm the question.

Create a new secondactivity:

public class Secondactivity extends activity{    @Override    protected void onCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_second);        TextView TextView = (TextView) Findviewbyid (r.id.tv);        Textview.settext (This.tostring ());        Button button = (button) Findviewbyid (R.id.btn_second);        Button.setonclicklistener (New View.onclicklistener () {            @Override public            void OnClick (View v) {                Intent Intent = new Intent (secondactivity.this, mainactivity.class);                StartActivity (intent);}}        );}    }

Change the previous mainactivity jump code to:

Intent Intent = new Intent (mainactivity.this, secondactivity.class);                StartActivity (Intent);

At this time, Firstactivity will jump to secondactivity,secondactivity and will jump to firstactivity. The demo results are as follows:

We see that the serial numbers of the two mainactivity are different, proving that a new mainactivity instance was generated when jumping from secondactivity to mainactivity. Schematic diagram is as follows:

We see that when jumping from secondactivity to mainactivity, the system discovers that there are firstactivity instances, but not at the top of the stack, and then regenerates an instance.
This is the Singletop startup mode, and if a corresponding activity instance is found to be at the top of the stack, it is reused and no new instances are generated.

This startup mode is usually applied to the interface that is displayed after receiving the message, for example, QQ will pop up activity after receiving the message, and if you come to 10 messages at a time, you cannot play 10 activity at a time.

3, Singletask

Based on the above we modify the properties of the mainactivity android:launchmode= "Singletask", the results are as follows:

We note that in the above process, the serial number of the mainactivity is constant, but the secondactivity serial number is not unique, indicating that a new instance was not generated when jumping from secondactivity to mainactivity. However, a new instance is generated when jumping from mainactivity to secondactivity.

Secondactivity jump to Mainactivity after the change of the stack structure, we notice that the secondactivity disappeared, yes, in this jump process, the system found that there is a firstactivity instance, and then no longer generate a new instance, Instead, the activity instances above the mainactivity are all stacked, and the mainactivity becomes the top object of the stack and appears before the screen. Perhaps friends have doubts, if the secondactivity is also set to Singletask mode, then the secondactivity instance can not be unique? In our example is not possible, because each time from secondactivity jump to mainactivity, secondactivity instances are forced out of the stack, the next time mainactivity jump to Secondactivity, The existing secondactivity instance cannot be found, so a new instance must be generated. But if we have thirdactivity, let secondactivity and thirdactivity jump to each other, then the secondactivity instance can be guaranteed unique.
This is the Singletask mode, if a corresponding activity instance is found, the other activity instances above the activity instance are all out of the stack, so that the activity instance becomes the top of the stack object and appears before the screen.

4, SingleInstance

This startup mode is special because it enables a new stack structure, places the activity in the new stack structure, and guarantees that no other activity instances will enter.
We modified Mainactivity's launchmode= "standard", secondactivity launchmode= "SingleInstance", because of the multiple stack structure involved, We need to show the ID of the current stack structure in each activity, so we add the following code for each activity:

TextView TextView = (TextView) Findviewbyid (r.id.tv);        Textview.settext ("Current task ID:" + this.gettaskid ());

The results are as follows:

We found that the two activity instances were placed in different stack structures, and the schematic diagram of the singleinstance is as follows

When we see the jump from mainactivity to secondactivity, we re-enable a new stack structure to place the secondactivity instance, then press the back key again to return to the original stack structure , the lower half of the figure is shown in secondactivity again to jump to mainactivity, this time the system will generate a mainactivity instance in the original stack structure, and then back two times, notice, did not exit, But to return to the secondactivity, why? Because when we jump from secondactivity to mainactivity, our starting point becomes the stack structure where the secondactivity instance resides, so we need to "go back" to this stack structure.

If the Mainactivity instance is created in the task stack of application 1, if Application 2 also activates mainactivity, then no creation is required, two apps share the activity instance, for example, your browser is open and another app accesses the browser. will be accessed directly in the current browser, otherwise open the browser. This saves system resources. (If you have multiple browsers in your phone, you need to select one, and the selected one is already open.)

Code Download: http://download.csdn.net/detail/jycboy/9747445

Application Scenarios:

Singletop is suitable for receiving notifications to launch the content Display page. For example, a news client's news content page, if it receives 10 news feeds, is annoying to open a news content page each time.

Singletask is suitable as a program entry point. For example, the browser's main interface. Regardless of how many apps launch the browser, only the main interface is started once, the rest will go onnewintent, and the other pages above the main interface will be emptied. Previously opened page, open the previous page is OK, no longer new.

The singleinstance is suitable for pages that need to be separated from the program. such as alarm reminders, separate alarm alarms from alarm settings. SingleInstance do not use in the middle page, if used in the intermediate page, jump transfer problems, such as: A-B (singleinstance)-C, after the full exit, this start, first opened is B.

Onnewintent ()

When you encounter an app's activity for multiple calls to start, multiple calls want only one instance of activity to exist, which requires the activity's onnewintent (Intent Intent) method. As long as you add your own onnewintent (intent) implementation in the activity plus the manifest in the activity settings lanuchmode= "Singletask".

Onnewintent () is very useful, when the activity first starts the execution of OnCreate ()---->onstart ()---->onresume () and other subsequent life cycle functions, also said The first activation activity does not execute to onnewintent ().  And then, if you want to start the activity again, that's the execution of Onnewintent ()---->onresart ()------>onstart ()----->onresume (). if the Android system releases the existing activity due to insufficient memory, the activity is restarted when it is called again (oncreate)---->onstart ()---->onresume (), and so on.

When calling to Onnewintent (intent), you need to use setintent (intent) in Onnewintent () to assign the intent to the activity. Otherwise, the subsequent getintent () is to get old intent.

protected void Onnewintent (Intent Intent) {super.onnewintent (Intent); setintent (Intent);//must store the new Intent Unle SS Getintent () would return the old one Processextradata ();}

Don't forget that the system may kill the Activity in the background at any time, if this happens, then the system will call the OnCreate method, instead of calling the Onnewintent method, a good solution is to onCreate and onnewintent method, call the same method that processes the data, as follows:

public void OnCreate (Bundle savedinstancestate) {  super.oncreate (savedinstancestate);  Setcontentview (r.layout.main);  Processextradata ();}
protected void Onnewintent (Intent Intent) {  super.onnewintent (Intent);   Setintent (intent);//must Store the new intent unless getintent () would return the old one  processextradata ()}private VO ID Processextradata () {  Intent Intent = Getintent ();  Use the data received here}

Activity Series Articles:

Android Activity Series Summary (i)--activity overview

Android Activity Series Summary (ii)--task and return stack

Android Spin Screen-The best solution for working with activity and asynctask (processing runtime changes)

Activity's overview screen (overview screens)

Android Activity Series Summary (iii)--activity four types of startup modes

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.