Analysis on Activity Startup Mode in Android deep dialysis, androidactivity

Source: Internet
Author: User
Tags stack pop

Analysis on Activity Startup Mode in Android deep dialysis, androidactivity
Preface:

The Activity startup mode is a basic and easy to ignore problem, but it has a deep understanding of this issue and is very helpful for programmers to write a stable and efficient Android program. Today, under B's guidance, we made a good exploration of the Activity Startup Mode and Intent Flags. You can say that if you are not familiar with or understand how to use the Activity startup mode or Flags, in the future, you will be troubled by actual development. Let's go back and study this section again. For example, why did some clients crash, there is still one or more interfaces for this application. If you are familiar with this chapter and understand it accurately, this error will not occur.

Exploration history:

What is stack?

Activity Stack

Task

Activity Startup Mode

Contact Activity stack and Task

Intent Flags

7.Activity-related attributes taskAffinity

 1.What is stack?

1.1Stack

Stack is a common data structure. The stack only allows access to the elements at the top of the stack. the stack is like a bullet shuttle (). Each time, you can only get the things at the top of the stack, for a stack, you can only access the top elements of the stack each time, so that other elements below the top elements of the stack can be protected. "first-in-first-out" or "later-in-first-out" is a major feature of the stack. The elements of the advanced stack always have to wait until the elements of the later-in-stack exit the stack. recursion uses the system stack to temporarily Save the temporary results and protect the temporary results.

 

1.2Stack)

Stack definition Stack is a linear table that only inserts and deletes operations at one end of the table.

(1) This end is usually referred to as the Top and the Bottom of the stack ).

(2) when there are no elements in the table, it is called an empty stack.

(3) the stack is a linear table of Last In First Out (LIFO. Stack modification is based on the principle of "back-to-first-out. Each deletion (rollback) is always the "latest" element in the current stack, that is, the last element to be inserted (into the stack), and the first element to be inserted is placed at the bottom of the stack, it cannot be popped up until the end.

 

1.3Stack operations: Stack pressure and elastic Stack

 

2. ActivityStack in

Android management is mainly implemented through the Activity stack. When an Activity is started, the system pushes it to a specific stack according to its configuration, and the system is running. When you click "return" or "FINISH ()", the Activity will be pushed out of the stack and destroyed accordingly. It can be known according to the lifecycle of the Activity, if the Activity in the currently displayed stack is not popped up (that is, the ondestory method of the Activity is called), when a new Activity is opened through Intent, the newly opened Activity is pushed to the top of the stack. figure (1)

 

Figure (1)

3. Task

A Task is the stack of an Activity. In short, a Task is a set of Activity components that are clustered in stack mode, recording users' behaviors. (Only the Startup Mode of the Activity is mentioned here)

 

4. ActivityStartup Mode

Property: android: launchMode

Purpose: use the main configuration fileAndroidThe launchMode attribute of the activity in Manifest. xml determines how the Activity starts.

Description: There are four modes, which work with the FLAG_ACTIVITY _ * variable of the Activity Flags in the Intent object to determine how the Activity starts to process the Intent.

Four modes:

①"Standard"-- Default mode
②"SingleTop"
③"SingleTask"
④"SingleInstance"

The following examples illustrate their differences:

A.Standard:

The default Loading Method of the Activity. This method starts creating a new activity instance and pushes the instance to the stack (whether or not the activity already exists in the Task stack, and call the OnCreate () method of the new Activity ..

For example, if the sequence in the stack is a B cd and D jumps to A through Intent, the structure in the stack is changed to a B C D, the display order of the return button is d c B A, which is destroyed in sequence. For example, (2)

One-sentence memory: whether or not the stack has been created, it will create a new stack and place it at the top of the stack and display it, calling the oncreate method.

Use Case: The default Activity startup mode.

Figure (2)

B.SingleTop:

Assume that a B C D already exists in the stack.

SingleTop mode.

1) The current App displays D or the stack top is D. If you need to enable D through Intent at this time, a new D instance will not be created, instead, it calls the D at the top of the stack and calls its onNewIntent method (note that it is not the oncreate method. The Oncreate method is called only when a new instance Activity is created) therefore, the stack structure is still a B C D. For example, (3)

Figure (3)

Thinking: So, let's think about it. When will this happen? It seems that there is a conflict between the currently displayed or stack-top activity and opening the same activity through Intent. Is this usage and necessary?

There is a cloud in the old saying: Everything has its own way. android provides such a usage, so there must be some truth. As for how to apply and how to apply it, it remains to be verified by readers. Here we just give a reference, however, this scenario can be used to demonstrate its effectiveness.

For example, if the current app stack is at the top of the stack A, A Message notification will pop up and the Message notification needs to be opened through Intent. When we click this message notification to open, this scenario is reproduced. instead of creating A new A, it will reuse the at the top of the stack and execute the onNewIntent method.

2) The current App displays D or the stack top is D. If B needs to be enabled at this time, because B is not at the top of the stack, therefore, A new B instance is created, pushed to the stack, and the onCreate method of the newly created B is called. The structure becomes a B c d B. For example, (4)

Figure (4)

One-sentence memory: only the to be opened is on the top of the stack, so A new A will not be created and the onNewIntent method will be called. If the to be opened is not on the top of the stack, then, no matter whether A is in the stack or not, A new A will be created and placed on the top of the stack, and the onCreate method will be executed.

 C.SingleTask:

In singleTask mode, only one instance corresponding to the Activity exists in the Task stack.

For example, the current stack structure is a bc d.

In this case, D opens B through Intent, and the stack structure is changed to a B. C and D are destroyed by the stack pop-up, that is to say, all instances on B are destroyed. Instead of creating a new B instance, instead of using the original B in the stack, the onNewIntent () method of the original B is called. For example, (5), (6)

Figure (5)

Figure (6)

Experience: This mode is common. In the activity stack, because the application needs to open multiple identical or different activities, the Activity stack will become larger and larger, as a result, the memory consumed will become larger and larger. If Activity is configured with this attribute, it will be invincible. What will it do? If B C D E… is enabled after A is enabled... Wait, if you need to open A at this time, but want to destroy B C D E... This attribute meets your needs. At this time, you will find that your memory usage drops, because B C D E... It has been destroyed.

Experience: Of course, it doesn't mean that if a singleTask is set, everything is universal. As mentioned earlier, each method has its own principle. What singleTask wants to do is, it is displayed that the existing Activity in the current stack is not re-created, but reused. If there is an Activity in the stack that needs to be opened, destroy other activities on the Activity in the stack first, expose an existing Activity and execute its onNewIntent method.

Of course, if the current stack does not exist, create a new one and place it at the top of the stack.

One sentence: As long as A exists in the stack, it will destroy all (excluding A) above A, display and reuse A, and execute the onNewIntent method. Otherwise, create A new A and place it at the top of the stack.

D. singleInstance:

In singleInstance mode, a new Task stack is created.

For example, the current stack structure is a bc d.

Open E through Intent in D (E mode is singleInstance), A new Task stack 2 will be created, and the structure in stack Task 1 is still a B C D, the structure in stack 2 is E, and E is displayed on the screen.

This mode is usually used only when another App is opened. For example, you can call an application that has a high usage rate and consumes resources. Open the app, Sina Weibo, and other clients. For example, (7)

Figure (7)

5. ActivityStack and Task contact

A Task is a set of Activity components that are aggregated in stack mode. Similar to a container that fills the Activity, the first Activity to be added is located at the bottom of the container, the Last part is at the top of the container, while the Activity retrieved from the Task is First taken from the top, and the Last part is to add the Activity at the beginning. This is the Last In First Out) mode, and the sequence of the Activity in the Task can be controlled. When the Activity jumps, Intent Flag can be used to set the creation method of the new activity (the use of Intent Flag is involved here ).

 

6. Intent Flags

Flags: indicates the Intent flag. It is often used in Activity scenarios. It is closely related to the Activity startup mode. To put it simply, the effective combination of flag (usually "|" used in combination) determines how to open the Activity.

The following lists the Flags attributes related to the topic of this article:

(1) -- Intent. FLAG_ACTIVITY_NEW_TASK (default)

The default jump type, which creates a new Activity.

(2) -- FLAG_ACTIVITY_SINGLE_TOP

This FLAG is equivalent to singletop in startup mode. For more information, see singletop.

(3) -- FLAG_ACTIVITY_CLEAR_TOP

The Activity started with this FLAG will bring up all the activities above the Activity to be started (including itself) to the stack space. For example, the original stack structure is a B c d, jump from D to B, release order is d c B, and re-create B and place it on the top of the stack, the structure in the stack is changed to a B. (This method can be used to close multiple activities)

Experience: you need to destroy multiple activities before A in the stack, but you do not want to destroy A. You need to combine FLAG_ACTIVITY_CLEAR_TOP and FLAG_ACTIVITY_SINGLE_TOP.

(4) -- FLAG_ACTIVITY_CLEAR_TASK

The Flag must be in API level 11 or later versions and be used with FLAG_ACTIVITY_NEW_TASK.

This identifier is used to release all the activities in the current stack, and then create a new activity object and place it on the top of the stack.

For example, if the stack contains a B c d, You need to jump from D to B, release d c B a in sequence, create B, and place it on the top of the stack.

7. ActivityRelated attributes taskAffinity

The android: taskAffinity attribute in the Activity is described as follows:

Activity is an affinity of a Task. An Activity with the same affinity theoretically belongs to the same Task (from the user's perspective, it is the same "application "). The affinity of a Task is determined by its root Activity.
Affinity determines two things: the re-host Task of the Activity (refer to the allowTaskReparenting feature) and the Task of the Activity host started with the FLAG_ACTIVITY_NEW_TASK flag.
By default, all activities in an application have the same affinity. You can set this feature to reorganize them, or even place the Activity defined in different applications into the same Task. To make it clear that the Activity does not host a specific Task, set a null string for this feature.
If this feature is not set, the Activity inherits from the application settings (refer to the taskAffinity feature of the <application> element ). The default affinity of the application is the package name set in the <manifest> element.

Android: taskAffinity: this attribute of the Activity takes effect only when the Intent with FLAG_ACTIVITY_NEW_TASK flag is used to start the Activity. The system switches tasks with the same Task affinity to the foreground, start the Activity. Otherwise, the Activity is still running in the Task where it is started.


How to ensure that the number of Activity instances is unique (Activity Startup Mode)

Public class ActA extends Activity {/** Called when the activity is first created. * // @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); TextView textView = new TextView (this);/*** standard mode: * <p> * when the current code block is used to start the Activity, A new Activity instance is created every time. * Because the default startup mode (standard mode) is used, we can identify whether to be a new Activity by using the hash code in the TextView text below * click back to view the previously started Activity instance in sequence, similar to the stack exit operation, the startup process is similar to the stack operation ** singleTop mode: * <p> * when running, you will find that the number of times you press the button is the same ActiA instance, because the instance is on the top of the stack, no new instance will be created. if it is rolled back, the application * singleTop mode will be withdrawn and can be used to solve the problem of multiple identical activities at the top of the stack. if A Activity jumps to Activity B and * A Activity, the behavior is the same as that of standard. A new instance of Activity A is created when Activity B jumps to Activity, because the top of the stack at that time was not A Activity instance ** singleTask mode: * <p> * When intent arrives and the singleTask mode Activity needs to be created, the system will check whether there are instances of the Activity in the stack *. if any, send intent directly to it. ** singleInstance mode: * <p> * First, let's talk about the concept of Task. if it is a Swing or Windows program, there may be multiple Windows that can be switched, but you cannot reuse the Windows in your program. * Note that the binary code is reused directly, instead of the source code-level call after you get the api. android can achieve this by allowing other programs to directly reuse your * Activity (similar to windows of desktop programs ). android introduces the concept of Task to provide this mechanism. * <p> * a Task can be considered as a stack and put into multiple activities. for example, to start an application, Android creates a Task and * starts the entry Activity of the application *, it is the one configured as main and launch in intent-filter (see the effect of multiple application installations in an APK file). This Activity is the Root * Activity, other activities may be called on its interface. If these activities follow the above three modes *, they will also be in this stack (Task), but the instantiation policies are different. the verification method is to call and print the taskId of the Activity: * <p> * TextView textView2 = new TextView (this); * textView2.setText ("task id:" + this. getTaskId (); * You will find that no matter the Activity is switched, taskId is the same. ** Of course, you can also put another person's Activity in this single Task stack, for example, googl ...... remaining full text>

What are the four startup modes of Activity?

The Activity startup mode can be specified by the <activity> element attribute in the AndroidManifest. xml file. There are four modes in total:
<Activity android: name = "ActivityMain" android: launchMode = "singleTask"> </activity>
1 standard
2 singleTop
3 singleTask
4 singleInstance

In these four models, there are two categories: standard and signleTop, and singleTask and signleInstance.

The instance of the Activity of the standard and singleTop attributes can belong to any Task and can be located anywhere in the Activity stack. A typical scenario is that the code of a task executes startActivity (). If the passed Intent object does not contain the FLAG_ACTIVITY_NEW_TASK attribute, the specified Activity will be called by the task, to load the Activity stack of the task. The difference between standard and singleTop is that a standard Activity creates a new instance when it is called, and all instances process the same Intent object. However, for singleTop Activity, if the called task already has an Activity at the top of the stack, no new instances will be created. The task uses the Activity instance at the top of the stack to process Intent objects. In other words, if the called task contains a singleTop Activity not at the top of the stack, or the Activity whose top is singleTop at the stack is not the currently called task, A new Activity object will still be created.

SingleTask and singleInstance modes can only be used to start a task. In this mode, an Activity is always at the bottom of the Activity stack and can only be instantiated once. The difference between the two is: for an Activity in singleInstance mode, if such Activity exists in the Activity stack of the task, it will be the only Activity in the stack, the Intent received by the current task is processed by it, and other activities started by it are started in other tasks. For SingleTask-mode Activity, it is at the bottom of the stack, other activities can be created at the top of the template. However, if the Intent object sent to the Activity is not at the top of the stack, the Intent object will be discarded, however, the interface will still switch to the current Activity.

In multi-Activity development, activity jumps between applications or reusable activities with other applications. You may want to jump to an existing activity instance instead of multiple duplicate activities. We can use four activation modes of activity to meet different needs:
Standard default mode --------- intent is created, and a new instance is created each time.

SingleTop -------- intent comes, and every time a new instance is created, there is only one exception: when the activity at the top of the stack is exactly this

No new instance is created when you create an instance of activity. This solves the problem of stack top reuse. Think about it. You press the back key twice to exit... the rest of the text>

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.