Functional verification of Android activity startup mode

Source: Internet
Author: User

have been watching someone else write the startup mode, found that most of the online content is plagiarism to plagiarism, until recently saw the development of art this book, found before the start of the understanding of the mode is too simple, a lot of things are not considered, in order to deepen understanding, so decided to do their own to verify the four start mode. Of course we also start with the simplest boot mode verification.

For printing convenience, define a base activity that prints the current activity's log information in its OnCreate method and Onnewintent method, mainly including the task that belongs to, the hashcode of the current class, and the value of taskaffinity. After that, the activity that we tested was directly inherited by the activity

 Public  class baseactivity extends appcompatactivity {    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); LOG.E ("TAG","===========================================oncreate======================================================= =="); LOG.E ("TAG","OnCreate"+ GetClass (). Getsimplename () +"TaskId:"+ gettaskid () +"Hascode:"+ This. Hashcode ());    Dumptaskaffinity (); }@Override    protected void onnewintent(Intent Intent) {Super. Onnewintent (Intent); LOG.E ("TAG","===========================================onnewintent==================================================== ====="); LOG.E ("TAG","Onnewintent"+ GetClass (). Getsimplename () +"TaskId:"+ gettaskid () +"Hascode:"+ This. Hashcode ());    Dumptaskaffinity (); }protected void dumptaskaffinity(){Try{Activityinfo info = This. Getpackagemanager (). Getactivityinfo (Getcomponentname (), packagemanager.get_meta_data); LOG.E ("TAG","taskaffinity:"+info.taskaffinity); }Catch(Packagemanager.namenotfoundexception e)        {E.printstacktrace (); }    }}
    • Standard mode

      This mode is the default startup mode, that is, the standard mode, without specifying the startup mode, the system uses this mode to start the activity by default, each time the activity is started will be rewritten to create a new instance, regardless of the existence of this instance, this mode, Who initiates the activity of the pattern, which is in the task stack of the activity that initiated it.


Create a new activity and declare it in the manifest file
<activity android:name=".standard.StandardActivity"          android:launchMode="standard"    ></activity>

For standard mode,Android:launchmode can not be declared, because the default is standard.

Standardactivity code below, the entry activity has a button to enter the activity, the activity has a button to start the standardactivity.

 Public  class standardactivity extends baseactivity {    PrivateButton Jump;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_standard);        jump= (Button) Findviewbyid (r.id.jump); Jump.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {Intent Intent =NewIntent (standardactivity. This, Standardactivity.class);            StartActivity (Intent);    }        }); }}
Look at the GIF dynamic graph, a bit of stuttering, make a look, we first enter standardactivity, enter and then click * * Test standard** button, and then press four times return key constantly return. [Write a description of the picture here] (http://img.blog.csdn.net/20151023135647145) The output log is as follows! [Write a description of the picture here] (http://img.blog.csdn.net/20151023135714701) can see the log output four times standardactivity and once mainactivity, From mainactivity into the standardactivity once, and then we pressed three buttons, a total of four times the standardactivity log, and the task stack is the ID of 62, which also verifies that * * who initiated the activity of the mode, The activity belongs to the task stack of the activity that started it, because the standardactivity is mainactivity, and Mainactivity's TaskID is 62, So the start of the standardactivity should also belong to the ID 62 of this task, the subsequent 3 standardactivity is standardactivity This object started, so should also be 62, so taskid are 62. And the hashcode of each activity are different, stating that they are distinct instances, that is, each time an activity is started, it will be rewritten to create a new instance * *
    • Singletop, stack top multiplexing mode

In this mode, if the new activity is already at the top of the stack, the activity will not be rewritten and its onnewintent method will be called. If there is no instance of the activity at the top of the stack, the situation is the same as standard mode.

The singletopactivity code is similar to standardactivity, except that you remember to modify the startup mode after manifest text.

<activity android:name=".singletop.SingleTopActivity"              android:launchMode="singleTop"        >

Similar to standard mode, direct paste output log

We see that except for the first time into the activity of the singletopactivity, the output is the OnCreate method of the log, followed by calls to the Onnewintent method, and did not call the OnCreate method, And the hashcode of the four logs are the same, stating that there is only one instance of the stack. This is because when the first entry, the stack does not have the instance, then create, the next three times the discovery stack top has this instance, is directly reused, and calls the Onnewintent method. So what if there is an instance in the stack, but the instance is not at the top of the stack?

We first go from mainactivity to singletopactivity, then jump to otheractivity, and then jump back from otheractivity to Singletopactivity, Then jump from singletopactivity to singletopactivity to see the log of the whole process.

We saw a new Singletopactivity object when we entered the singletopactivity from Mainactivity, and the task ID is the same as mainactivity. Then, when jumping from singletopactivity to otheractivity, a new otheractivity is created, and there are three activity in the task, from the bottom of the stack to the top of the stack is mainactivity, Singletopactivity,otheractivity, at this point, if you jump to singletopactivity, even if there are singletopactivity instances in the stack, But still will create a new singletopactivity instance, this point from the above log hashcode can be seen, at this time the top of the stack is singletopactivity, if you jump to singletopactivity, The singletopactivity of the top of the stack is reused, and the Onnewintent method of the singletopactivity is called. This is the whole process of the above log.

To summarize the above content

    • Standard startup mode is the default startup mode, and each time an activity is started, a new instance is created, regardless of whether or not an instance of the activity is already in the stack.
    • Singletop mode is divided into 3 different cases
      • When an instance of the activity already exists in the current stack and the instance is at the top of the stack, the instance is not created, but the instance of the top of the stack is reused, and the intent object is passed in, and the Onnewintent method is recalled.
      • When an instance of the activity is already in the current stack, but the instance is not at the top of the stack, its behavior is the same as the standard startup mode, and a new instance will still be created
      • When an instance of the activity does not exist in the current stack, its behavior is the same as standard startup mode.
    • Both standard and Singletop startup modes Create a new activity instance on the original task stack, and do not start a task, and you specify the taskaffinity property immediately.

So what is the taskaffinity attribute, which can be easily understood as a task dependency.

    • This parameter identifies the name of the task stack to be used by the activity, by default the name of the task stack required for all activity is the app's package name.
    • We can specify the Taskaffinity property of each activity to override the default value individually
    • The affinity of a task is determined by the taskaffinity of the root activity (root activity) of the task.
    • Conceptually, activity with the same affinity (that is, activity that sets the same Taskaffinity property) belongs to the same task.
    • Set an empty string for an activity's taskaffinity, indicating that the activity does not belong to any task.

It's important. The Taskaffinity property does not have any effect on the standard and Singletop modes, and immediately you specify the attribute as a different value, which does not create a new task in both startup modes

We specify that the previous examples of the taskaffinity are different values, the entry activity is not specified (no default value, that is, the package name)

<activity android:name=". Standard. Standardactivity "android:launchmode=" Standard "android:taskaffinity=" Cn.edu.zafu.lifecycle.standard " >                    </activity><activity android:name=". Singletop. Singletopactivity "android:launchmode="singletop "android:taskaffinity=" Cn.edu.zafu.lifecycle.singletop " >                    </activity>

Start each of these two activity to see the log output

We see that the taskaffinity value of the entry activity is the package name, which is not specified by default. Then the taskaffinity values of standardactivity and singletopactivity were overwritten by us, respectively, with different values, but when the two activity was started, the task stack was not created, but started directly in the original task. This shows that the taskaffinity has no effect on these two startup modes. In fact, this property is mainly used in conjunction with the Singletask startup mode. Next we look at the startup mode, which can be said that the startup mode is the most complex.

    • Singletask, that is, in-stack reuse mode

This model is very complex and has a variety of combinations. In this mode, if an instance of the activity is present in the stack, the activity is reused, regardless of whether it is at the top of the stack, when it is reused, the activity above it is all out of the stack, and the Onnewintent method of the instance is recalled. In fact, this process still has a task stack matching, because this mode starts, will be in the task stack you need to find instances, the task stack is specified by the Taskaffinity property.
If the task stack does not exist, the task stack is created.

Specify activity as Singletask mode

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

Now we do not specify any taskaffinity property, do a similar singletop to it, that is, from the entrance mainactivity into the singletaskactivity, and then jump to otheractivity, And then jump back to singletaskactivity. Look at the log of the whole process.

When we go from Mainactiviyty to singletaskactivity and then into Otheractivity, there are 3 activity instances in the stack, and singletaskactivity is not at the top of the stack, Instead of creating a new singletaskactivity when otheractivity jumps to singletaskactivity, the instance is reused, and the Onnewintent method is recalled. And the original otheractivity out of the stack, specifically see the following information, using the command adb shell Dumpsys activity activities can be viewed

Running activities (most recent first):
Taskrecord{434c6d90 #77 a=cn.edu.zafu.lifecycle u=0 sz=2}
Run #2: activityrecord{4358c850 u0 cn.edu.zafu.lifecycle/.singletask.singletaskactivity T77}
Run #1: activityrecord{43576720 u0 cn.edu.zafu.lifecycle/. Mainactivity T77}

You can see that there are only two activity in the current stack, that is, the activity on top of singletaskactivity in the original stack is out of stack.

We see the start of an activity using Singletask startup mode, which is still started in the original task. In fact, we do not specify the Taskaffinity property, which is the same as the default value, which is the package name, the name of the task created when Mainactivity starts is the package name, because Mainactivity also does not specify Taskaffinity, And when we start singletaskactivity, we first look for the existence of the required task stack, that is, the value specified by Taskaffinity, which is the package name, found, no longer creates a new task, but is used directly. The instance is reused when there is an activity instance in the task, which is the stack-in reuse mode.

At this point, if we specify the taskaffinity value of singletaskactivity.

<activity android:name=".singleTask.SingleTaskActivity"          android:launchMode="singleTask"          android:taskAffinity="cn.edu.zafu.lifecycle.singleTask"    ></activity>

or the previous operation. But the log will become different.

We see that the taskid of the task stack that singletaskactivity belongs to has been transformed, that is, a new task has been opened, and the subsequent otheractivity is running on that task.

Printing out the information also proves that there are two different tasks

Running activities (most recent first):
taskrecord{441ab678 #79 a=cn.edu.zafu.lifecycle.singletask u=0 Sz=1}
Run #3: activityrecord{432fa178 u0 cn.edu.zafu.lifecycle/.singletask.singletaskactivity t79}
Taskrecord{43ccd2a8 #78 a=cn.edu.zafu.lifecycle u=0 Sz=1}
Run #2: Activityrecord{42d5e7a8 u0 cn.edu.zafu.lifecycle/. Mainactivity t78}

What happens if we specify Mainactivity's Taskaffinity property and singletaskactivity?

Yes, it is the same as they do not specify anything.

At this point, we have the following conclusions

    • Singletask startup mode When you start activity, you will first look for a task stack that has a corresponding name based on taskaffinity
      • If it does not exist, a new task is created and a new activity instance is created to stack into the newly created task
      • If present, get the task stack to find out if the activity instance exists in the task stack
        • If there is an instance, the activity instance above it is stacked, and then the Onnewintent method of the activated activity instance is recalled
        • If the instance does not exist, create a new activity and merge it into the stack

In addition, we can set the activity in two different apps to the same taskaffinity, although in different applications, the activity is assigned to the same task

Let's create another application, specifying that its taskaffinity is the same as the previous one, both cn.edu.zafu.lifecycle.singleTask

        <activity android:name=".OtherActivity"                  android:launchMode="singleTask"                  android:taskAffinity="cn.edu.zafu.lifecycle.singleTask"            >        </activity>

Then launch an app, let him jump to the activity, then press the home button backstage, launch another app to enter the activity, look at the log

We see that the singletaskactivity and otheractivity that specify the same taskaffinity are launched into the same task, and the TaskID are all 274.

    • SingleInstance mode

This pattern has all the features of the singletask pattern, and the difference is that the activity in this mode occupies a single task stack, with global uniqueness, that is, an instance of the whole system. Activity initiated in SingleInstance mode is a singleton in the entire system, and if an instance is already in place when the Activiyt is started, it will be dispatched to the foreground and reused for this instance.

Add an activity that declares the following

        <activity android:name=". SingleInstance. Singleinstanceactivity "android:launchmode=" SingleInstance " >                              <intent-filter>                <action android:name="cn.edu.zafu.lifecycle"/>                <category android:name="Android.intent.category.DEFAULT"/>            </intent-filter>        </activity>

Use the following method to launch it in two applications, respectively

new Intent();intent.setAction("cn.edu.zafu.lifecycle");startActivity(intent);

Do the same as the last time, view the log

We see that when the first application starts singleinstanceactivity, because the instance does not exist in the system, a new task is created, pressing the home key and then using another app to enter the activity, since an instance already exists in the system. No new task is created, the instance is reused directly, and the Onnewintent method is recalled. It can be seen from their hashcode that this is the same instance.

The summary of the above content is

    • Activity initiated by SingleInstance mode has global uniqueness in the system.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Functional verification of Android activity startup mode

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.