Interpreting Android's tasks and back stacks

Source: Internet
Author: User
Tags home screen

This document is translated from Android official documentation, combined with your own tests, organized as follows.

Overview

An application usually includes multiple activities, each activity needs to specify a specific function, and sometimes it needs to start other activity. If there is an activity in a mail app that displays a list of content, when the user selects a message content, a new activity is opened that displays the content of the message.

An activity can even start the activity of other applications on the device. For example, if our program wants to send a message, we can send use that object to respond to all activities that satisfy the requirement by defining a intent object with information such as an action and an email address and content, even if it is not in an application. When the message is finished, you can still return to the activity. So the user feels that our program has the ability to send mail. Even though activities comes from different applications, the Android system can still combine them with the same tasks (Task).

The task is a collection of activities (lowercase means activity instances, which are also the meanings below) that are used to accomplish a specific task for a user. These activities are arranged on the back stack, and activities are arranged in the stack in an open order that satisfies the "LIFO principle".

Most tasks are initiated from the home screen of the device, and when the user taps the program icon on the Home screen, the program's tasks come to the foreground. If the program is not recently started, a new task is created and the main activity of the program is placed at the top of the stack on the back stack as the root activity.

When the activity starts another activity, the new activity is in the stack, at the top of the stack, and gets the user focus. The previous activity remains on the back stack, but enters the stopped state (the system saves the activity's UI state information at this time). When the user presses the back key, the activity at the top of the stack is out of the stack (that is, the activity is destroyed), and then the previous activity reaches the top of the stack, that is, regain the user focus (the state before the restore) and enter the resumed state. The order of the activities in the back stack will never change, only from the top of the stack, when the new activity is started, and when the back button is used, the back stack satisfies the LIFO principle. The above description is shown in detail:

If the user presses the back key all the time, the activities is removed in turn until it returns to the home screen (or to the activity that initiated the task). When the back stack is empty, the corresponding task for that stack does not exist.

A task is a tightly integrated unit that can be moved to the foreground when it is newly created, or it can be returned to the background by pressing the home key. When the task is in the background, all the activities in the back stack go into the stopped state, but that back stack is still intact-except that the task loses the user focus. As shown (Task B receives a user request to be displayed in the foreground, and task A enters the background, waiting for the user to request the display again):

The background task can switch to the foreground, so the user will see the task that was previously left. For example, there are three activities in the stack of current task A, and when the user presses the Home key, task a enters the background and then launches another program, the system creates a new task B for the program. When the user interacts with the program and then presses the home key back to the screen, Task B also enters the background. When the user re-opened the first program, task a returned to the foreground, task A's back stack of three activities order did not change, the top of the stack activity into the running state. Users can still switch to Task B via the home button, or start other tasks. This is an example of Android multi-task switching.

Note: There can be multiple background tasks at the same time, but when the system is low on memory, some activities may be destroyed to recover memory space.

Because the activities order in the back stack never changes, if our program allows the user to start the specified activity from multiple activities, The instance of the activity is created each time it is started (rather than moving the previous activity to the top of the stack). This can cause the same activity to be instantiated multiple times, as shown in:

When you press the back key, it is displayed in order in the back stack (each activity has its own UI state, and their UI state is not necessarily the same even for different instances of the same activity).

So how can you avoid instances being created more than once, and this part will be introduced later.

Let's summarize the behavior patterns of activities and tasks by default:

    • When activity a starts activity B, activity a enters the stopped state, but the system still holds the status information of a, such as the contents of the text box input. If the user presses the back key in B, a will re-enter the running state.
    • When the user leaves a task through the home key, the current activity enters the stopped state, and the task enters the background. The system holds the status information for all activities in the back stack. When the user then re-opens the program, the task goes to the foreground and displays the activity at the top of the stack.
    • If the user presses the back key, the current activity is removed from the back stack and the system is destroyed. Activity that is currently at the top of the stack will go into a running state. When the activity is destroyed, the system will no longer save any of its state information.
    • Each activity can be instantiated several times, regardless of whether it is in a task.
Save Activity status information

We know that when activity enters the stopped state, the activity status information is saved by default by the system. Therefore, when the user activates the activity the next time, the activity can return to its original state. However, we should take the initiative to save the state information in case the activity of the stopped state is destroyed by the system and rebuilt.

When the activity enters the stopped state, the system may completely destroy the activity in the case of low memory. In this case, the system no longer saves information for our activity, but the system still knows where the activity is located in the back stack, but the activity must be recreated when the activity reaches the top of the stack. In order to avoid losing the information before the user, we should proactively save this information (covered in activity onSaveInstanceState() ).

Interested in this section can be found in my previous translated article: Interpreting Android Activity (1) Basics

management tasks

Android manages tasks and back stacks in the way above, putting all the activities on the same task, and the back stack being managed by the LIFO principle. This approach is suitable for most applications, and we don't have to worry about how the activity in the task relates to the task and how it is stored in the back stack. However, there are times when we might want to break this default behavior. For example, we want to store the newly started activity in a new task instead of the existing one. Or, when you start an activity, we want to use that instance that already exists in the back stack instead of creating one. Or, we want to clear all the activity in the back stack except for the bottom of the activity when the user leaves the task.

These implementations, or other implementations, can be implemented by setting the properties of the tag in the manifest file <activity> or by configuring the flag property of the intent object when the activity is started.

In the <activity> label, there are several properties that you can use:

    • taskAffinity
    • launchMode
    • allowTaskReparenting
    • clearTaskOnLaunch
    • alwaysRetainTaskState
    • finishOnTaskLaunch

In intent, we can use:

    • FLAG_ACTIVITY_NEW_TASK
    • FLAG_ACTIVITY_CLEAR_TOP
    • FLAG_ACTIVITY_SINGLE_TOP

In the following section, we discuss the above properties specifically.

Note: It is still important to remind you that the default startup mode is suitable for most programs, and if we modify it, make sure that the back key and other navigation fallback keys are available, and avoid conflicts with what the user wants.

Defining the startup mode

The startup mode allows us to define how activity is associated with the current task, and we can define it in two ways:

    1. Using the manifest file
      When you declare an activity in a manifest file, we can specify how the activity is associated with the task at startup.
    2. Using the Intent Property flag
      When called startActivity() , we can set the flag property in the intent object to specify how the new activity is associated with the current task.

For example, if activity a initiates activity b,b you can define how you are associated with the current task, and a can also ask how B is associated with the current task. If B has already defined an association in manifest, and a also sets flag in intent, then the Start method in request intent of a will overwrite the setting in the manifest of B.

Note: Some startup modes can be specified in manifest, but not in intent. Similarly, some startup modes are available in intent, but not in manifest. The following are specific.

Using the manifest file

When the activity is declared in the manifest file, we can <activity> launchMode set the activity's startup mode through the tag's properties, with the following four kinds of values:

  • standard
    The default mode. Each time you start the activity, the system creates a new instance and always puts it into the current task. This startup mode activity can be instantiated several times, and a task can contain multiple instances of the pattern activity.
  • singleTop
    Stack top single mode. If the activity to be started is at the top of the stack at the current back stack, the system will pass the intent object to the activity's onNewIntent() method (which then calls to onResume() start activity again) without creating a new instance. This startup mode activity can be instantiated several times, and a task can contain multiple instances of the pattern activity (only if the top position of the stack is not the activity).
    Note: Activity in this mode cannot be returned to the previous state by the back key ( onNewIntent() the state before the call).
  • singleTask
    Task single mode. The system creates a new task and puts the activity in the bottom position of the back stack of the new task. However, if the activity is already present in the existing task (including all tasks in the current task, about why the activity might be described in the property in the current task taskAffinity ), then the system calls the activity directly onNewIntent() (after calling Onrestart () method to start activity again (all activity on top of the activity will stack up and then put the activity on top of the stack) instead of creating a new activity. The activity of this mode only has one instance in a task. The default, which is then initiated after the activity, is placed in the same back stack as the activity.
    This mode is taskAffinity affected by the properties, which taskAffinity are described in.

    For example, the browser program built into the Android system declares that the activity of its own web page is always open in its own task, which is <activity> achieved by setting the startup mode in the tag singleTask . This means that when our program opens the browser, its activity is not placed in our current task, but instead launches a new task, and if the browser already has a task in the background, it switches the task directly to the foreground to process the intent object.

  • singleInstance
    Single instance mode. And the singleTask same, except for one thing: The system does not add another activities to the task that contains the pattern activity, that is, the task has a single activity. Other activities that are opened by the activity will be placed in another task. This mode is not taskAffinity affected by attributes

Regardless of whether the activity starts in a new task or is started in the current task, the back key is returned to the previous activity, which 之前的activity is not necessarily the activity that initiates the current activity. Instead, the previous one in the back stack is returned to the activity that initiated the current activity if it does not exist.
For example, if the activity is in a startup mode singleTask , and the activity is in a background task, the entire task will be switched to the foreground. When you press the back key at this point, it returns to the next activity (if present) in the return stack of the current task, instead of returning to the activity that initiated the activity, as described:

More information can be found in the activity tag introduction

Note: launchMode setting the activity's startup mode will be overridden by the intent property flags. This section is followed by an introduction.

Use the Intent Property flags

startActivity()You can set the start mode of the activity that will be started by setting the flags of the passed intent object, and flag has the following values:

    • FLAG_ACTIVITY_NEW_TASK

      Start the activity in a new task. If the activity exists in the other existing tasks, the task is switched directly to the foreground and the intent object is passed to the activity onNewIntent() .
      This model singleTask is the same, and is subject to other constraints.

    • FLAG_ACTIVITY_SINGLE_TOP

      If the activity is activated at the top of the stack on the back stack, the activity is called directly onNewIntent() .
      This pattern is the singleTop same.

    • FLAG_ACTIVITY_CLEAR_TOP

      If the active activity exists in the current task, all the activities above the activity are all out of the stack, and the intent object is passed to the activity for onNewIntent() processing instead of creating the activity.
      This pattern does not correspond in the Launchmode.

      FLAG_ACTIVITY_CLEAR_TOPMore cases are and are FLAG_ACTIVITY_NEW_TASK used in combination. If you use this combination, you can locate the activity that exists in the other task and stack all of it. But FLAG_ACTIVITY_NEW_TASK I also have this function, do not know what the meaning here,,,,

      Note: If the activity initiated under this flag is a standard pattern, not only the activity above the activity will be out of the stack, it will also be out of the stack itself, and re-create a new activity to process the incoming intent object. This is because in the standard mode, a new activity is always created to handle the intent object.

Handling affinities

Affinity indicates which task the activity is more willing to attach to, and by default, all activities in the same application have the same affinity. So activities in the same application would prefer to be in the same task. We can also change the activity of the affinity, different programs in the activities can have the same affinity, the same program activities affinity can be different.

We can <activity> modify the affinity value by the properties of the tag taskAffinity .

The taskaffinity value is a string that you can specify as an arbitrary value (at least one in the string . , or an INSTALL_PARSE_FAILED_MANIFEST_MALFORMED error), but not the same as the package name of the application, because the system uses the package name as the default affinity value.

Affinity mainly has the following two kinds of application environment:

  • When the intent object that initiates the ACTIVITY contains flag_activity_new_task (or declares a startup mode of Singletask in the manifest file) When
    is called startactivity () When the activity is started, the activity is placed in the current task by default. We have described above when the intent object contains Flag_activity_new_task or when the startup mode is declared Singletask in the manifest file. The system creates a new task to hold the activity or directly use the activity from other existing tasks, but this does not necessarily happen. When an existing task (including the current task) has the same affinity as the activity, the activity is placed in a task that has the same affinity as it. If not, a new task will be created to hold the activity.

    This way creates a new task management activity, and when the user presses the home key, we must ensure that the user can navigate back to the task through other navigation. If we want to invoke the activity of an external task, we must set the activity to start in one of these two ways, while ensuring that the user has a separate way to go back to the startup task, such as by launching the icon.

  • When you set the activity's allowTaskReparenting property to true
    In this case, activity can be moved from the task that started it to a task that has the same affinity value as the activity, provided that the task that has the same affinity value as the activity is switched to the foreground.

    For example, in the weather forecast program, where an activity is used to display weather conditions, the activity and all activities of the program have the same affinity value and are allowTaskReparenting true. When our own application launches the activity, the activity is in the same task as our program. However, when the weather forecast program is switched to the foreground, the ctivity will be transferred to the task of the weather forecast program and displayed.

Attention:

    1. When an '. apk file contains more than one application, we should set the affinity value of activities to associate the specific "application".
    2. Activity with different affinity values can be placed in the same back stack. For example singleTask , when activity is initiated standard and inactive, the activity is singleTop placed on the same back stack.
Clear Back Stack

If a user leaves a task for a long time, the system clears all activity except the lowest activity in the task. When the user returns to the task, only the bottommost activity is saved. This is the system default behavior, because after such a long time, the user is likely to forget the things that were doing at the time, and back again very likely to want to do other things.

You can <activity> change this by setting the following properties in the label:

    • alwaysRetainTaskState

If you set this property of the bottommost activity to true , the task will keep all the activities in the back stack, even after a long time.

    • clearTaskOnLaunch

If this property of the lowest activity is set to true , then as long as the user leaves the task, the system clears all activities on top of the activity, no matter how long it takes to leave. In other words, and alwaysRetainTaskState Conversely, each time the user returns the task is the initial state, even if the user has just left.

    • finishOnTaskLaunch

This property clearTaskOnLaunch is similar, but it works on a single activity, not on the entire task. When this property of an activity is set to true , if the user leaves the current task, the activity is destroyed, even at the bottom of the activity.

Start a task

We can <activity> use the following settings as a task entry in the label:

<activity ... >    <intent-filter ... >        <action android:name="android.intent.action.MAIN" />        <category android:name="android.intent.category.LAUNCHER" />    </intent-filter>    ...</activity>

The icon and name of the activity with the intent filter will be the icon and name of the application (on the Home screen). The icon can start or go back to the application's entry activity.

We have to make sure that after leaving the task, the user can then start the task again through the icon. For this reason, singleTask and singleInstance the activities must be the entry activity of the program, otherwise, the user will not be able to return to the task after leaving the task (because the program's entry task (started by the icon) is not the task), thus causing data loss. Of course, it is not entirely impossible to find the task, and we can also retrieve it on overview screen, and the overview screen will be translated later.

Interpreting Android's tasks and back stacks

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.