Android Summary-Activity task and return stack, save activity status

Source: Internet
Author: User

Tasks and return stacks

An application usually contains a lot of activity, and each activity should be designed to be a component that has specific functionality and can be manipulated by the user. In addition, the activity should also be able to start each other. For example, a mail application might contain an activity to display a mailing list, and when a user clicks on one of the messages, another activity is opened to show the specific contents of the message.

In addition, an activity can even initiate activity in other applications. For example, if your app wants to send an email, you can define a intent with a "send" action, and pass in some data, such as the email address, the message content, and so on. Thus, if an activity in another application declares that it can respond to such intent, then the activity is opened. In the current scenario, this intent is intended to send mail, so the write activity in the mail application should be opened. When the message is sent out, it still goes back to your application, which makes it seem as if the activity that you just wrote was part of your application. So, even though many of the activity comes from different applications, the Android system can still seamlessly combine them, and the reason for this is that the activity is in one of the same tasks.

A task is a collection of activity that uses a stack to manage its activity, which is called the back stack, and the order of activity in the stack is stored in the order in which they are opened.

The home interface of the phone is where most tasks start, and when the user clicks on an app icon on the home screen, the app's task is transferred to the foreground. If the application does not currently have any task (indicating that the app has not been started recently), the system will create a new task and put the app's main activity into the return stack.

When an activity initiates another activity, the new activity is placed at the top of the stack and will receive the focus. The previous activity remains in the return stack but is in a stopped state. When the user presses the back key, the topmost activity in the stack is removed and the previous activity is returned to the topmost position. The order of activity in the return stack will never change, we can only add activity to the top of the stack, or remove the activity at the top of the stack. Therefore, the return stack is a typical last-in, first-out data structure. The timeline is a very clear way to show us the state change of multiple activity in the return stack:


If the user presses the back key all the time, the activity in the return stack is removed from each other until it is eventually returned to the home screen. When all the activity in the return stack is removed, the corresponding task does not exist.

Tasks can also be transferred to the background, in addition to being transferred to the foreground. When a user opens a new task, or clicks the home button to return to the home screen, the task is moved to the background. When the task is in the background state, all activity in the return stack goes to the stop state, but the activity's order in the stack remains intact, as shown in:


At this point, the user can also switch any background task to the foreground, so the user should see the activity that was at the top of the task before leaving. For example, there are three activity in the current task a stack, and now the user presses the home key and then clicks the icon on the desktop to launch another application. When the system comes back to the desktop, the task A is actually in the background, and then when another application starts, the system will open a new task (Task B) for the program. When the user has finished using the program, press the home button again to return to the desktop, this time the task B also entered the background. Then the user re-opened the first use of the program, this time task A will return to the foreground, a task stack of three activity will still remain in the order, the top of the activity will be re-run state. After that, the user can still switch back to Task B via the home key or multitasking key, or start more tasks, which is an example of multi-task switching in Android.

Because the order of activity in the return stack will never change, so if you allow multiple portals in your application to start the same activity, a new instance of the activity will be created each time it is started. Instead of moving the following activity to the top of the stack. This can easily lead to the creation of a problem where the same activity is likely to be instantiated many times, as shown in:


However, if you do not want the same activity to be instantiated multiple times, then of course it is possible, and we will begin to discuss if this function is implemented, now let's briefly summarize the default tasks and activity behavior:

    • When activity a starts activity B, activity a goes into a stopped state, but the system still retains all its relevant information, such as the scrolling position, the contents of the text box input, and so on. If the user presses the back key in activity B, activity A will return to the running state.

    • When the user leaves a task through the home key, the task enters the background and all activity in the return stack goes to the stop state. The status of these activity is retained so that the next time the user re-opens the application, the background task can be extracted directly to the foreground and the previous top activity is restored.

    • When the user presses the back key, the current topmost activity is removed from the return stack, the removed activity is destroyed, and the previous activity is in the top position of the stack and enters the active state. When an activity is destroyed, no state information is kept for it.

    • Each activity can be instantiated many times, even in different tasks.

Save status of activity

When an activity is destroyed by the system in order to recover memory, the activity object is destroyed, so the system simply cannot keep its state intact while continuing the activity, but must reconstruct the activity object when the user returns to activity. However, users do not know that the system destroyed the activity and then rebuilt it, so they are likely to think that the activity state has no change. In this case, you can implement another callback method to save information about the activity State to ensure that important information about the activity state is retained: Onsaveinstancestate ().

The system calls Onsaveinstancestate () before the Activity becomes easy to destroy. The method passes a Bundle where you can use methods such as putstring () and Putint () to hold information about the Activity state in the form of a name-value pair. Then, if the system terminates your application process and when the user returns to your activity, the system rebuilds the activity and passes the Bundle to OnCreate () and Onrestoreinstancestate (). You can use either of these methods to extract your saved state from the Bundle and restore the Activity state. If no state information is needed to recover, the Bundle passed to you is null (this happens if the Activity was first created).



In both cases, the activity can remain intact when the user focus is regained: The system rebuilds the activity,activity after the activity has been destroyed and the system must restore the previously saved state; The Activity status remains intact.

Note: There is no guarantee that the system will call Onsaveinstancestate () before destroying your activity because there is no need to save the state (for example, when a user leaves your activity using the "back" button because the user's behavior is explicitly closed Activity). If the system calls Onsaveinstancestate (), it will be called before OnStop () is called and may be made before calling OnPause ().

However, even if you do nothing and do not implement Onsaveinstancestate (), the onsaveinstancestate () default implementation of the activity class also restores part of the activity state. Specifically, the default implementation invokes the corresponding Onsaveinstancestate () method for each view in the layout, so that each view can provide information about itself that should be saved. Almost every gadget in the Android framework implements this method as needed to automatically save and restore any visible changes to the UI when the Activity is rebuilt. For example, the EditText gadget saves any text that is entered by the user, and the checkbox gadget saves the check box in the checked or unchecked state. You only need to provide a unique ID (via the Android:id property) for each gadget that you want to save its state. If the gadget does not have an ID, the system cannot save its state.

You can also explicitly block a view within a layout from saving its state by setting the Android:saveenabled property to False or by calling the Setsaveenabled () method. You should not normally disable this property, but you may need to do this if you want to restore the state of the Activity UI in a different way.

Note: Because the system is not guaranteed to call Onsaveinstancestate (), you should only use it to record the transient of the Activity (the state of the UI)-Never use it to store persistent data, but use OnPause () to leave the activity Store persistent data (for example, data that should be saved to the database).

management tasks

The way Android systems manage tasks and return stacks, as described above, is to put all the activated activity into a single task, managed by a "LIFO" stack. This is not a problem in most cases, and developers do not have to worry about how the activity in the task is stored in the return stack. But, if you want to break this default behavior, say, when you start a new activity, you want it to exist in a separate task, rather than in the existing task. Or, when starting an activity, if the activity already exists in the return stack, you want to be able to move the activity directly to the top of the stack instead of creating an instance of it. Or, you want to be able to erase all the activity in the return stack except for the bottom of the activity. These features, and even more, can be achieved by setting the attributes of the elements in the manifest file, or by configuring intent flag when the activity is started.

In an element, there are several properties that can be used:

Taskaffinity

Launchmode

Allowtaskreparenting

Cleartaskonlaunch

Alwaysretaintaskstate

Finishontasklaunch

Among the intent, the following flags are more commonly used:

Flag_activity_new_task

Flag_activity_clear_top

Flag_activity_single_top

Note: Most apps must not disrupt activity and the default behavior of tasks: If you determine that your activity has to modify the default behavior, when you use the Back button to navigate back to the activity from other activities and tasks, Be careful and be sure to test the availability of the Activity during startup. Make sure the test navigation behavior is likely to conflict with the user's expected behavior.

Defining the 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:

The intent identification priority is higher than the startup mode defined in Androidmanifest.

Working with manifest files

When you declare an activity in a manifest file, you can use the Launchmode attribute of the element to specify how the activity should be associated with the task.

The Launchmode property specifies instructions about how Activity should be started into a task. There are four types of startup modes that you can assign to the Launchmode property:

  • "Standard" (default mode)
    Default. The system creates a new instance of the activity in the task that initiates the activity and transmits the Intent to it. Activity can be instantiated multiple times, and each instance can belong to a different task, and a task can have multiple instances.

  • "Singletop"
    If an instance of activity already exists at the top of the current task, the system transmits Intent to it by calling the instance's Onnewintent () method instead of creating a new instance of the activity. Activity can be instantiated multiple times, each of which can belong to a different task, and a task can have multiple instances (provided that the activity at the top of the return stack is not an existing instance of the activity).

    Effect with intent Add "Flag_activity_single_top"

    Note: When creating a new instance for an activity, the user can press the Back button to return to the previous activity. However, when an existing instance of Activity processes a new Intent, the user cannot return to the Activity state by pressing the back button until the new Intent arrives at Onnewintent ().

  • "Singletask"

    This startup mode indicates that the system creates a new task and puts the activated activity in the bottom position of the new task. However, if an instance of the activity already exists in the existing task, then the system will not create its instance again, but will call its onnewintent () method directly. An activity declared as such a startup mode will only have one instance in the same task. Note that what we call the start activity here is to start activity in other applications, because the "singletask" mode will create a new task by default only activity that starts another program. Starting an activity in your own program will still use the same task, as explained in the section below dealing with affinity.

    Effect with intent Add "Flag_activity_new_task".

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

  • "SingleInstance"
    This startup mode is somewhat similar to "Singletask", except that the system does not add other activity to the task that is declared as "singleinstance" activity. That is, there is always only one activity in this activity, and other activity that is opened by the activity is put into another task.

In another example, Android's built-in browser program declares that its activity on the Web page should always be open in a separate task, which is done by setting the "Singletask" startup mode in the element. This means that when your program is ready to open the Android built-in browser, the newly opened activity will not be placed in your current task, but will start a new task. If the browser has a task in the background, the task will be switched to the foreground.

In fact, whether the activity starts in a new task or starts in the current task, the return key will always take us back to the previous activity. However, there is a particular case where the activity specifies that the startup mode is "Singletask" and initiates an activity in another application, when the activity is found to be in a background task. The entire background task will be switched directly to the foreground. Pressing the Back button now takes precedence over the current most foreground task (which has just been switched from the background to the foreground) and shows the situation in a more vivid way:

Using the Intent flag

When you start activity, you can modify the default association of activity and its tasks by adding the appropriate flag to the Intent passed to StartActivity (). Flags that you can use to modify the default behavior include:

    • Flag_activity_new_task
      With this flag set, the new start activity will be placed in a new task (similar to "Singletask", but not exactly), and of course the discussion here still starts with activity in other programs. The flag's role is usually to simulate a launcher behavior, which is to list what a push can start, but every activity that starts is running in its own separate task.

      equivalent to Launchmode set to "Singletask"

    • Flag_activity_single_top
      If the activity being started is the current activity (at the top of the return stack), the existing instance receives a call to Onnewintent () instead of creating a new instance of the activity.

      equivalent to Launchmode set to "Singletop"

    • Flag_activity_clear_top

      If the activity that is being started is already running in the current task, all activity at the top of the current task is destroyed, and this Intent is passed to the activity's recovered instance (now at the top) through Onnewintent () instead of starting the A new instance of Activity.

      Case used alone: ABCD start B, will destroy instances of B and B to become AB, B re-execute OnCreate-OnStart
      When used with Flag_activity_single_top, B does not destroy only the instances above B, then B executes onnewintent, OnStart
      With Flag_activity_new_task, it is the singletask effect.

Handling affinity

Affinity can be used to specify which task the activity prefers to attach to, and by default all activity in the same application has the same affinity, so the activity is more inclined to run in the same task. Of course, you can also change the affinity value of each activity, which can be achieved by the taskaffinity attribute of the element.

The Taskaffinity property receives a string parameter that you can specify as an arbitrary value (at least one in my test string), but must not be the same as the package name of the application, because the package name is used as the default affinity value.

Affinity has the following two types of application scenarios:

    • When you invoke the StartActivity () method to start an activity, the default is to put it into the current task. However, if a flag_activity_new_task flag is added to the intent (or the ACTIVITY is declared in the manifest file, the startup mode is "Singletask"), The system will attempt to create a separate task for the activity. But the rule is not only so simple, the system will detect the activity to start affinity and the current task affinity is the same, if the same will put it into existing tasks, if different will be to create a new task. The affinity of all activity in the same program is the same by default, which is why the same application does not create a new task for the activity even if it is declared as "Singletask".

    • When you set the activity's Allowtaskreparenting property to True, the activity has the ability to transfer the task. Specifically, an activity is now in a certain task, but it has the same affinity value as another task, and when the other task switches to the foreground, the activity can be transferred to the current task.

      That's an example of an image point, such as a weather report program, which has an activity that is designed to display weather information, the activity and all other activity of the weather program, the exact same affinity value, It also sets the Allowtaskreparenting property to True. At this point, your own application launches the activity using intent to display the weather information, so this activity should be in the same task as your application. But when the weather-forecasting program is switched to the foreground, the activity is then moved to the task of the weather-forecast program and displayed because they have the same affinity value, and the Allowtaskreparenting property is set to true.

Found a good activity on the Nuggets. Four examples of startup modes are explained, suggest to look: thoroughly understand the four major startup modes of activity

Empty return stack

How the user switches the task to the background after a long period of time, the system will be the task in addition to the bottom of the activity of all other activity out of all. When the user returns to this task, the activity at the bottom will be restored. This is the default behavior of the system, because after such a long period of time, the user is likely to forget what was being done, then back to the task, basically should be to do something new.

Of course, since the default behavior, it means that we have a way to change, set the following properties in the element can change the default behavior of the system:

    • alwaysretaintaskstate
      If this property of the lowest activity is set to True, the default behavior described above will not occur, and all activity in the task will remain after a long period of time.

    • Cleartaskonlaunch
      If this property of the bottommost activity is set to true, all other activity on top of the underlying activity will be erased as long as the user leaves the current task and returns again. In short, it is a completely opposite mode of working with Alwaysretaintaskstate, which guarantees that every time a task is returned it will be an initialization state, even if the user has only been away for a short period of time.

    • Finishontasklaunch
      This property is similar to Cleartaskonlaunch, but it does not work on the entire task but on a single activity. If an activity sets this property to true, the activity will be erased once the user leaves the current task and returns again.

Some content forwarded from: http://blog.csdn.net/guolin_blog/article/details/41087993

Android Summary-Activity task and return stack, save activity status

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.