android的Tasks and Back Stack

Tasks and Back Stack

An application usually contains multiple activities. Each activity should be designed around a specific kind of action the user can perform and can start other activities. For example, an email application might have one activity to show a list of new email. When the user selects an email, a new activity opens to view that email.

An activity can even start activities that exist in other applications on the device. For example, if your application wants to send an email, you can define an intent to perform a "send" action and include some data, such as an email address and a message. An activity from another application that declares itself to handle this kind of intent then opens. In this case, the intent is to send an email, so an email application's "compose" activity starts (if multiple activities support the same intent, then the system lets the user select which one to use). When the email is sent, your activity resumes and it seems as if the email activity was part of your application. Even though the activities may be from different applications, Android maintains this seamless user experience by keeping both activities in the same task.

 

A task is a collection of activities that users interact with when performing a certain job. The activities are arranged in a stack (the "back stack"), in the order in which each activity is opened.

 

The device Home screen is the starting place for most tasks. When the user touches an icon in the application launcher (or a shortcut on the Home screen), that application's task comes to the foreground. If no task exists for the application (the application has not been used recently), then a new task is created and the "main" activity for that application opens as the root activity in the stack.

 

When the current activity starts another, the new activity is pushed on the top of the stack and takes focus. The previous activity remains in the stack, but is stopped. When an activity stops, the system retains the current state of its user interface. When the user presses the Back button, the current activity is popped from the top of the stack (the activity is destroyed) and the previous activity resumes (the previous state of its UI is restored). Activities in the stack are never rearranged, only pushed and popped from the stack—pushed onto the stack when started by the current activity and popped off when the user leaves it using the Back button. As such, the back stack operates as a "last in, first out" object structure. Figure 1 visualizes this behavior with a timeline showing the progress between activities along with the current back stack at each point in time.

PS:看来返回按钮可以直接destroy当前activity。activity的存在是堆栈,后进先出。如果按home键则不会destroy。

diagram_backstack

Figure 1. A representation of how each new activity in a task adds an item to the back stack. When the user presses the Back button, the current activity is destroyed and the previous activity resumes.

 

If the user continues to press Back, then each activity in the stack is popped off to reveal the previous one, until the user returns to the Home screen (or to whichever activity was running when the task began). When all activities are removed from the stack, the task no longer exists.

 

A task is a cohesive unit that can move to the "background" when users begin a new task or go to the Home screen, via the Home button. While in the background, all the activities in the task are stopped, but the back stack for the task remains intact—the task has simply lost focus while another task takes place, as shown in figure 2. A task can then return to the "foreground" so users can pick up where they left off. Suppose, for example, that the current task (Task A) has three activities in its stack—two under the current activity. The user presses the Home button, then starts a new application from the application launcher. When the Home screen appears, Task A goes into the background. When the new application starts, the system starts a task for that application (Task B) with its own stack of activities. After interacting with that application, the user returns Home again and selects the application that originally started Task A. Now, Task A comes to the foreground—all three activities in its stack are intact and the activity at the top of the stack resumes. At this point, the user can also switch back to Task B by going Home and selecting the application icon that started that task (or by touching and holding the Home button to reveal recent tasks and selecting one). This is an example of multitasking on Android

Figure 2. Two tasks: Task B receives user interaction in the foreground, while Task A is in the background, waiting to be resumed.

diagram_multitasking

Note: Multiple tasks can be held in the background at once. However, if the user is running many background tasks at the same time, the system might begin destroying background activities in order to recover memory, causing the activity states to be lost. See the following section about Activity state.

 

Because the activities in the back stack are never rearranged(导致activity可能重复出现,因为无法把之前的相同的activity调整到栈top), if your application allows users to start a particular activity from more than one activity, a new instance of that activity is created and pushed onto the stack (rather than bringing any previous instance of the activity to the top). As such, one activity in your application might be instantiated multiple times (even from different tasks), as shown in figure 3. As such, if the user navigates backward using the Back button, each instance of the activity is revealed in the order they were opened (each with their own UI state). However, you can modify this behavior if you do not want an activity to be instantiated more than once. How to do so is discussed in the later section about Managing Tasks.

diagram_multiple_instances

Figure 3. A single activity is instantiated multiple times.

打开一个task,new出几个activity,如果按Back button直到Home screen,则task没有activity,全部destroy。

如果按下Home button,直接回到Home screen,此时再launch其他application的话,stack里刚才的activity会一直存在,

并且新的application产生task也会存在。此时,后来的activity里也许有和前面activity是同一个activity,这样就是multiple

times。

 

To summarize the default behavior for activities and tasks:

  • When Activity A starts Activity B, Activity A is stopped, but the system retains its state (such as scroll position and text entered into forms). If the user presses the Back button while in Activity B, Activity A resumes with its state restored.
  • When the user leaves a task by pressing the Home button, the current activity is stopped and its task goes into the background. The system retains the state of every activity in the task. If the user later resumes the task by selecting the launcher icon that began the task, the task comes to the foreground and resumes the activity at the top of the stack. (launch一个application,然后Home_button,再打开同一个application)
  • If the user presses the Back button, the current activity is popped from the stack and destroyed. The previous activity in the stack is resumed. When an activity is destroyed, the system does not retain the activity's state.
  • Activities can be instantiated multiple times, even from other tasks.

Saving Activity State

As discussed above, the system's default behavior preserves the state of an activity when it is stopped. This way, when users navigate back to a previous activity, its user interface appears the way they left it. However, you can—and shouldproactively retain the state of your activities using callback methods, in case the activity is destroyed and must be recreated.  系统默认保存stopper的activity的状态,但是还是应该自己用回调方法主动保存activity的状态

When the system stops one of your activities (such as when a new activity starts or the task moves to the background), the system might destroy that activity completely if it needs to recover system memory. When this happens, information about the activity state is lost. If this happens, the system still knows that the activity has a place in the back stack, but when the activity is brought to the top of the stack the system must recreate it (rather than resume it). In order to avoid losing the user's work, you should proactively retain it by implementing the onSaveInstanceState() callback methods in your activity. 因为如果指望系统默认的那种保存状态的行为,很有可能系统为了释放内存,activity被destroy,当回到栈顶的时候,就必须recreate了。

For more information about how to save your activity state, see the Activities document.


 

Managing Tasks

The way Android manages tasks and the back stack, as described above—by placing all activities started in succession in the same task and in a "last in, first out" stack—works great for most applications and you shouldn't have to worry about how your activities are associated with tasks or how they exist in the back stack. However, you might decide that you want to interrupt the normal behavior. Perhaps you want an activity in your application to begin a new task when it is started (instead of being placed within the current task); or, when you start an activity, you want to bring forward an existing instance of it (instead of creating a new instance on top of the back stack); or, you want your back stack to be cleared of all activities except for the root activity when the user leaves the task.

 

You can do these things and more, with attributes in the <activity> manifest element and with flags in the intent that you pass to startActivity()1.manifest.xml里的<activity>属性  2.传给startActivity()的intent的flags

 

In this regard, the the principal <activity> attributes you can use are:

And the principal intent flags you can use are:

In the following sections, you'll see how you can use these manifest attributes and intent flags to define how activities are associated with tasks and how they behave in the back stack.

Caution: Most applications should not interrupt the default behavior for activities and tasks. If you determine that it's necessary for your activity to modify the default behaviors, use caution and be sure to test the usability of the activity during launch and when navigating back to it from other activities and tasks with the Backbutton. Be sure to test for navigation behaviors that might conflict with the user's expected behavior.

 

Defining launch modes

Launch modes: 决定一个新的activity实例是如何与当前task相互作用,就是一个新的activity怎么从task里出来。

allow you to define how a new instance of an activity is associated with the current task. You can define different launch modes in two ways:  有两种方式定义启动模式

  • Using the manifest file

    When you declare an activity in your manifest file, you can specify how the activity should associate with tasks when it starts.

  • Using Intent flags

    When you call startActivity(), you can include a flag in the Intent that declares how (or whether) the new activity should associate with the current task.

As such, if Activity A starts Activity B, Activity B can define in its manifest how it should associate with the current task (if at all) and Activity A can also request how Activity B should associate with current task. If both activities define how Activity B should associate with a task, then Activity A's request (as defined in the intent) is honored over Activity B's request (as defined in its manifest).  如果A和B都定义了B的launchMode,以A为准。

Note: Some launch modes available for the manifest file are not available as flags for an intent and, likewise, some launch modes available as flags for an intent cannot be defined in the manifest.  manifest表里定义的launch mode 比intent flags 可以定义的launch mode 要多。

 

Using the manifest file

 When declaring an activity in your manifest file, you can specify how the activity should associate with a task using the <activity> element's launchMode attribute.

 

 The launchMode attribute specifies an instruction on how the activity should be launched into a task. There are four different launch modes you can assign to thelaunchMode attribute: 可用的四种属性

"standard" (the default mode) Default. The system creates a new instance of the activity in the task from which it was started and routes the intent to it. The activity can be instantiated multiple times, each instance can belong to different tasks, and one task can have multiple instances.

这种是默认模式,activity可以被实例化多次,每一个实例可以属于不同的task,一个task可以拥有多种实例。

 

"singleTop" If an instance of the activity already exists at the top of the current task, the system routes the intent to that instance through a call to its onNewIntent() method, rather than creating a new instance of the activity. The activity can be instantiated multiple times, each instance can belong to different tasks, and one task can have multiple instances (but only if the activity at the top of the back stack is not an existing instance of the activity).

 如果一个activity的实例已经存在,且在当前task的顶端,系统会发送一个intent给那个实例的onNewIntent()方法,而不是创建一个新的activity实例。activity可以被实例化多次,每一个实例可以属于不同的task,一个task可以有多种实例(条件是:在栈顶的activity不是已经存在的activity的实例,如果是,则不会新建一个新的activity实例对象)。

For example, suppose a task's back stack consists of root activity A with activities B, C, and D on top (the stack is A-B-C-D; D is on top). An intent arrives for an activity of type D. If D has the default "standard" launch mode, a new instance of the class is launched and the stack becomes A-B-C-D-D. However, if D's launch mode is "singleTop", the existing instance of D receives the intent through onNewIntent(), because it's at the top of the stack—the stack remains A-B-C-D. However, if an intent arrives for an activity of type B, then a new instance of B is added to the stack, even if its launch mode is "singleTop".

这个举例已经说的很清楚了,假设堆栈里有A-B-C-D四个activity,D在top

1.来了一个D类型的intent,如果D的launch mode是standard,则会创建一个新的D的实例,此时:A-B-C-D-D

2.来了一个D类型的intent,如果D的launch mode是 singleTop,则现在的D实例会通过onNewIntent()接收intent,,并不会创建新实例,此时:A-B-C-D

3.来了一个B类型的intent,即使B的launch mode是singleTop,也会创建新的B实例,此时:A-B-C-D-B

结论:只是栈顶的singleTop类型的activity特殊一些,不在栈顶,或不是singleTop的话,都会创建新activity实例

 

 Note: When a new instance of an activity is created, the user can press the Back button to return to the previous activity. But when an existing instance of an activity handles a new intent, the user cannot press the Back button to return to the state of the activity before the new intent arrived in onNewIntent().

 如果创建了一个activity的新实例,可以通过Back button回到之前的activity,好比3里,从B返回D

如果已经一个已经存在activity的实例得到了一个intent,通过后退按钮,无法使它回到onNewIntent里intent到达之前的状态。

 

"singleTask"

        The system creates a new task and instantiates the activity at the root of the new task. However, if an instance of the activity already exists in a separate task, the system routes the intent to the existing instance through a call to its onNewIntent() method, rather than creating a new instance. Only one instance of the activity can exist at a time.

 系统创建了一个新的task并且创建一个新的activity根对象,如果这个activity已经有实例存在于另外的task里,系统就会将这个intent送给已经存在的这个activity对象的onNewIntent()方法,而不是创建一个新的对象。对这个activity来说,同一时刻只能有一个对象。 

Note: Although the activity starts in a new task, the Back button still returns the user to the previous activity.

 

"singleInstance".

Same as "singleTask", except that the system doesn't launch any other activities into the task holding the instance. The activity is always the single and only member of its task; any activities started by this one open in a separate task.

 

As another example, the Android Browser application declares that the web browser activity should always open in its own task—by specifying the singleTask launch mode in the <activity>element. This means that if your application issues an intent to open the Android Browser, its activity is not placed in the same task as your application. Instead, either a new task starts for the Browser or, if the Browser already has a task running in the background, that task is brought forward to handle the new intent.

 

Regardless of whether an activity starts in a new task or in the same task as the activity that started it, the Back button always takes the user to the previous activity. However, if you start an activity that specifies the singleTask launch mode, then if an instance of that activity exists in a background task, that whole task is brought to the foreground. At this point, the back stack now includes all activities from the task brought forward, at the top of the stack. Figure 4 illustrates this type of scenario.

diagram_backstack_singletask_multiactivity

Figure 4. A representation of how an activity with launch mode "singleTask" is added to the back stack. If the activity is already a part of a background task with its own back stack, then the entire back stack also comes forward, on top of the current task.

For more information about using launch modes in the manifest file, see the <activity> element documentation, where the launchMode attribute and the accepted values are discussed more.

 

Note: The behaviors that you specify for your activity with the launchMode attribute can be overridden by flags included with the intent that start your activity, as discussed in the next section.    属性可以被flags覆盖

 

Using Intent flags

When starting an activity, you can modify the default association of an activity to its task by including flags in the intent that you deliver to startActivity(). The flags you can use to modify the default behavior are:

 

FLAG_ACTIVITY_NEW_TASK      等同于singleTask Start the activity in a new task. If a task is already running for the activity you are now starting, that task is brought to the foreground with its last state restored and the activity receives the new intent in onNewIntent().

This produces the same behavior as the "singleTask" launchMode value, discussed in the previous section.

 

FLAG_ACTIVITY_SINGLE_TOP    等同于singleTop If the activity being started is the current activity (at the top of the back stack), then the existing instance receives a call to onNewIntent(), instead of creating a new instance of the activity.      

This produces the same behavior as the "singleTop" launchMode value, discussed in the previous section.

 

FLAG_ACTIVITY_CLEAR_TOP    没有属性与之对应 If the activity being started is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it are destroyed and this intent is delivered to the resumed instance of the activity (now on top), through onNewIntent()).

如果这个activity已经在当前task里运行,所有其他在它上面的activity都将被destroy,而不是新启动一个新的对象,此时,这个activity对象就在top了,并且intent通过onNewIntent()方法传入。

 FLAG_ACTIVITY_CLEAR_TOP is most often used in conjunction with FLAG_ACTIVITY_NEW_TASK. When used together, these flags are a way of locating an existing activity in another task and putting it in a position where it can respond to the intent.

 

Note: If the launch mode of the designated activity is "standard", it too is removed from the stack and a new instance is launched in its place to handle the incoming intent. That's because a new instance is always created for a new intent when the launch mode is "standard".

 

Handling affinities    处理activity关系

The affinity indicates which task an activity prefers to belong to. By default, all the activities from the same application have an affinity for each other. So, by default, all activities in the same application prefer to be in the same task. However, you can modify the default affinity for an activity. Activities defined in different applications can share an affinity, or activities defined in the same application can be assigned different task affinities.

 affinity说的是activity之间的亲和关系,默认状态下,同一个application里的activity关系更亲密,所以同一个application里的activity更愿意在同一个task里,但是,我可以更改这种默认的亲和关系,在不同application里定义的activity完全可以享有同样的affinity,或者同一application里的activity可以被分配不同的affinity。

 

You can modify the affinity for any given activity with the taskAffinity attribute of the <activity> element.

可以通过activity里的taskAffinity 属性来修改

 

The taskAffinity attribute takes a string value, which must be unique from the default package name declared in the <manifest> element, because the system uses that name to identify the default task affinity for the application.

 

The affinity comes into play in two circumstances:  要用到affinity的两种环境

1.When the intent that launches an activity contains the FLAG_ACTIVITY_NEW_TASK flag.

A new activity is, by default, launched into the task of the activity that called startActivity(). It's pushed onto the same back stack as the caller. However, if the intent passed tostartActivity() contains the FLAG_ACTIVITY_NEW_TASK flag, the system looks for a different task to house the new activity. Often, it's a new task. However, it doesn't have to be. If there's already an existing task with the same affinity as the new activity, the activity is launched into that task. If not, it begins a new task.

If this flag causes an activity to begin a new task and the user presses the Home button to leave it, there must be some way for the user to navigate back to the task. Some entities (such as the notification manager) always start activities in an external task, never as part of their own, so they always put FLAG_ACTIVITY_NEW_TASK in the intents they pass tostartActivity(). If you have an activity that can be invoked by an external entity that might use this flag, take care that the user has a independent way to get back to the task that's started, such as with a launcher icon (the root activity of the task has a CATEGORY_LAUNCHER intent filter; see the Starting a task section below).

 

2.When an activity has its allowTaskReparenting attribute set to "true".

In this case, the activity can move from the task it starts to the task it has an affinity for, when that task comes to the foreground.

For example, suppose that an activity that reports weather conditions in selected cities is defined as part of a travel application. It has the same affinity as other activities in the same application (the default application affinity) and it allows re-parenting with this attribute. When one of your activities starts the weather reporter activity, it initially belongs to the same task as your activity. However, when the travel application's task comes to the foreground, the weather reporter activity is reassigned to that task and displayed within it.

 

Tip: If an .apk file contains more than one "application" from the user's point of view, you probably want to use the taskAffinity attribute to assign different affinities to the activities associated with each "application".

 

Clearing the back stack

If the user leaves a task for a long time, the system clears the task of all activities except the root activity. When the user returns to the task again, only the root activity is restored. The system behaves this way, because, after an extended amount of time, users likely have abandoned what they were doing before and are returning to the task to begin something new. 长时间离开一个task,系统很有可能会把这个task除了root的activity全部destroy了,这样回到这个task的时候,就从root activity重新开始了。

 

There are some activity attributes that you can use to modify this behavior:

alwaysRetainTaskState   这样就会保存一个task的所有activity了 If this attribute is set to "true" in the root activity of a task, the default behavior just described does not happen. The task retains all activities in its stack even after a long period.   clearTaskOnLaunch        If this attribute is set to "true" in the root activity of a task, the stack is cleared down to the root activity whenever the user leaves the task and returns to it. In other words, it's the opposite of alwaysRetainTaskState . The user always returns to the task in its initial state, even after a leaving the task for only a moment.

如果一个task的Root activity将这个属性设置为“true”,离开这个task再回来的时候,会clear,就剩root activity。

通过startActivity再次调用此activity就会重新执行onCreate。

通过桌面laucher调用,则会把task里其他activities清除掉,执行onResume。

  finishOnTaskLaunch This attribute is like clearTaskOnLaunch , but it operates on a single activity, not an entire task. It can also cause any activity to go away, including the root activity. When it's set to"true", the activity remains part of the task only for the current session. If the user leaves and then returns to the task, it is no longer present.

如果activity设置了true,那么通过startActivity再次调用此activity就会重新执行onCreate。

 
Starting a task

You can set up an activity as the entry point for a task by giving it an intent filter with "android.intent.action.MAIN" as the specified action and "android.intent.category.LAUNCHER" as the specified category. For example:

   1:  <activity ... >      
   2:      <intent-filter ... >
   3:          <action android:name="" />
   4:          <category android:name="" />
   5:      </intent-filter>
   6:      ...
   7:  </activity>

An intent filter of this kind causes an icon and label for the activity to be displayed in the application launcher, giving users a way to launch the activity and to return to the task that it creates any time after it has been launched.

 

This second ability is important: Users must be able to leave a task and then come back to it later using this activity launcher. For this reason, the two launch modes that mark activities as always initiating a task, "singleTask" and ""singleInstance", should be used only when the activity has an ACTION_MAIN and a CATEGORY_LAUNCHER filter. Imagine, for example, what could happen if the filter is missing: An intent launches a "singleTask" activity, initiating a new task, and the user spends some time working in that task. The user then presses the Home button. The task is now sent to the background and is not visible. Now the user has no way to return to the task, because it is not represented in the application launcher.

For those cases where you don't want the user to be able to return to an activity, set the <activity> element's finishOnTaskLaunch to "true" (see Clearing the stack).

 

 

 

转载于:https://www.cnblogs.com/bevin-h/archive/2012/05/10/2494828.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值