1th Chapter Activtiy life cycle and startup mode

Source: Internet
Author: User

Total solution of life cycle of 1.1 activtiy

The life cycle of an activity is divided into two parts, one of which is the life cycle in a typical case, and the other is the life cycle in an abnormal situation. The so-called life cycle in a typical situation is the change in the life cycle that the activity undergoes in the context of the user's participation. , and the life cycle in an abnormal situation refers to the activity being destroyed and rebuilt because the activity is reclaimed by the system or because the configuration of the current device is changed.

Life cycle analysis in typical cases of 1.1.1

Under normal circumstances, the activity will experience the following life cycle.
(1) OnCreate: Indicates that activity is being created, which is the first method in the activity life cycle. In this method, we can do some initialization work, such as Call Setcontentview Load interface layout resources, initialize the data required for activity.
(2) Onrestart: Indicates that the activity is being restarted. In general, Onrestart is called when the current activity is never visible and becomes visible again. This situation is typically caused by user behavior, such as when the user presses the home button to switch to the desktop or opens a new activity, the current activity pauses, that is, OnPause and OnStop are executed, and then the user returns to the activity, This can happen.
(3) OnStart: The activity is being started and is about to start, when activity is already visible, but not in the foreground, and user interaction is not available. This time can actually be understood as activity has been shown, but we do not see.
(4) Onresume: The activity is already visible and appears in the foreground as well. To pay attention to this and onstart contrast, onstart and onreume are visible, but onstart when the activity is still in the background, onresume when the display to the foreground.
(5) OnPause: Indicates that the activity is stopping, normally the onstop will be called immediately thereafter. In special cases, if the time comes back to the current activity quickly, then the Onresume will be called. The OnPause method cannot perform too time-consuming operations because it affects the display of the new activity. It should be known that the old activity must be executed first, and the new activity's onresume will be executed.
(6) OnStop: The activity is about to stop, you can do some heavy recycling work, also not too time-consuming.
(7) Ondestory: The activity is about to be destroyed, which is the last callback in the activity life cycle, where we can do some recycling and release the final resources.
Under normal circumstances, activity has a common life cycle of only the above 7, more detailed description of the activity of the various life cycle of the transition process.

For, and then attach a specific description, divided into the following situations.
(1) First start of an activity: Oncreate->onstart->onresume
(2) When a user opens a new activity or switches to the desktop: Onpause->onstop, there is a special case where the current activity does not callback if the new activity uses a transparent theme OnStop
(3) When the user returns to the original activity again, the callback is as follows: Onrestart->onstart->onpause
(4) When the user presses the back key to rollback, the callback is as follows: Onpause->onstop->ondestory
(5) When the activity is re-opened after the system is reclaimed, the life cycle method callback process and (1), just like the life cycle method, does not mean that all processes are the same
(6) from the entire life cycle, OnCreate and ondestory are paired, identifying the creation and destruction of activity, and only one call is possible. From the activity is visible, OnStart and OnStop are paired, these two methods may be called multiple times as the user operates or the device screen is lit and extinguished, and from the perspective of whether the activity is viewed from the foreground, OnPause and Onresume are paired. Note here that OnStart and OnStop are callbacks from the perspective of activity visibility, and that OnPause and Onresume are callbacks from the angle class of whether the activity is located in the foreground, with the exception that there is no other obvious difference in actual use.

Life cycle analysis in 1.1.2 anomaly cases

1, Scenario 1: Resource-dependent system configuration changes resulting in activity being killed and recreated

For example: The screen of the phone is switched vertically
when the system configuration changes, the activity is destroyed, its onpause,onstop,ondestory are called, and the activity is terminated in exceptional circumstances, The system calls Onsaveinstancestate to save the state of the current activity. This method is called before OnStop. It should be emphasized that this method will only occur when the activity is terminated abnormally, and this method is not normally invoked. When the activity is recreated, the system calls the Onrestoreinstacestate "method after the call is OnStart" The bundle objects saved by the Onsaveinstancestate method are also passed to the Onrestoreinstacestate and OnCreate methods as parameters when the activity is destroyed by the exception. So we can use the OnCreate and Onrestoreinstacestate methods to determine if the activity has been rebuilt.
If it is rebuilt, it can be recovered by removing the data previously saved in the bundle object.
Note here that the bundle object can be received by both the OnCreate and Onrestoreinstacestate methods, but there is a difference between the two. Once the onrestoreinstacestate is called, its parameter bundle saveinstacestate is definitely a value, and we don't have to empty the extra. But OnCreate not, if the activity is normal start, the parameter bundle saveinstacestate is NULL, so you must be sentenced to empty operation.

At the same time, we should know that in the Onsaveinstancestate and Onrestoreinstacestate methods, the system automatically for us to do a certain amount of recovery work. When the activity needs to be recreated in an unusual situation, the system defaults to saving the view structure of the current activity, and restores the data for us after the activity restarts, such as the data entered by the user in the text box, the location of the ListView scroll, and so on. These view-related state systems can be restored to us by default. Specifically for a particular view system can restore us what data, we can see the source of the view. Like activity, each view has two methods, Onsaveinstancestate and Onrestoreinstacestate.
With regard to saving and restoring the view hierarchy, the system's workflow is this: When the activity is terminated unexpectedly, the activity calls Onsaveinstancestate to save the data, and the activity delegates the window to save the data. The window then delegates the top-level container above it to save the data. The top-level container is a viewgroup generally it is probably decorview. Finally the top-level container goes one by one to notify its child elements to save the data, so the entire data preservation process is complete. It can be found that this is a typical delegation of thought, the upper level of the delegation of the lower layer, the parent container entrusted child elements to deal with a thing, this idea is very common in Android. such as the drawing of view, event distribution, etc. are used in this idea. As for the recovery process of the data, this is no longer the case.

2, Scenario 2: Low-priority activity is killed due to insufficient resource memory

Priority of activity:
(1) Front desk activity– is interacting with the user activity, the highest priority;
(2) visible but non-foreground activity– such as activity popped a dialog box, resulting in activity visible but in the background can not interact with the user directly;
(3) Background activity– has been suspended activity, such as the execution of OnStop, the lowest priority;

When system memory is low, the system kills the process of the target activity in accordance with the above priority, and subsequently stores and recovers the data through Onsaveinstancestate and onrestoreinstacestate. If there are four components in a process, the process will be killed quickly. Therefore, some background work is not suitable to leave the four components and run in the background alone, so that the process is very easy to be killed. The better way is to put the background work into service to ensure that the process has a certain priority, so it will not be easily killed by the system.

Earlier, the configuration of the system changed and the activity was to be rebuilt. So is there a way not to rebuild it? The answer is yes. The system configuration contains a lot of items, but the usual is the locale (System language Switching), orientation (screen orientation) and Keyboardhidden (keyboard accessibility) These three options, other rarely used.
All we have to do is simply add the activity statement to the Androidmenifest.xml, and the code is as follows:

<?xml version= "1.0" encoding= "Utf-8"?>    <manifest xmlns:android="Http://schemas.android.com/apk/res/android"  package ="Com.test"android:versioncode= "1"android:versionname="1.0 ">                                <uses-sdk android:minsdkversion="8" />        <application android:icon= "@drawable/icon" android:label="@string /app_name ">            <activity android:name=". Testactivity "android:label=" @string/app_name "android:configchanges=  "Keyboardhidden|orientation">                                                        <intent-filter>                    <action android:name="Android.intent.action.MAIN" />                    <category android:name="Android.intent.category.LAUNCHER" />                </intent-filter>            </activity>        </Application>    </manifest>

In this case, the activity will not be rebuilt when the system configuration is changed. The Onsaveinstancestate and Onrestoreinstacestate methods are not invoked to save and restore data, instead the system calls the activity's Onconfigurationchanged method, This time we can do some of their own special treatment.

1.2 Activity's Startup mode

In the previous section we talked about the life cycle of activity in both standard and exceptional situations, and this section goes deep into the activity's startup mode and marker.

The Launchmode of 1.2.1 activity

(1) Standard: Normal mode, which is also the default mode for the system. In this mode, a new instance is created each time an activity is started, regardless of whether the instance exists. The life cycle of an instance that is created conforms to the life cycle of a typical activity. A task stack can have multiple instances, and each instance can belong to a different task stack. In this mode, who initiates the activity then the activity runs in the same stack as its activity. For example, a starts B, and if B is a standard mode, then B runs in A's task stack. Here the author speaks of a situation that we can look at. is the non-activity type of the context is not a task stack, so the non-activity type of context to start the standard mode amount of activity will be problematic. The solution is to add the FLAG_ACTIVITY_NEW_TASK flag bit to the activity to be started, so that when it is started, it will create a new task stack for it, and the activity to be started is actually started in Singletask mode.
(2) Singletop: Stack-set multiplexing mode. In this mode, if the new activity is already at the top of the stack, the activity will not be recreated, and its Onnewintent method will be called back, and we can read the current request's information through the parameters of this method.
(3) Singletask: In-stack multiplexing mode. This is a single-instance pattern. In this mode, as long as the activity is present in a stack, starting the activity multiple times does not rebuild the instance. Specifically, when an activity request with Singletask mode starts, such as activity A, the system first looks for a desired task stack, rebuilds a task stack if it does not exist, and then creates an instance of a to put a into the stack. If there is a task stack, then you will see if a has an instance in the stack, if the instance exists, then the system will be the activity instance above a bounce out, so that a at the top of the stack and then callback its Onnewintent method, if the instance does not exist, create an instance of a and press into the stack.
(4) Singleinstace: Single-instance mode. This is an enhanced singletask model, which, in addition to all the features of the Singletask model, reinforces the point that activity with this pattern can only be found in a single task stack.

The task stack has been said many times. Start with a parameter, taskaffinity, can be translated into task dependencies. This parameter identifies the name of the task stack that the activity requires. By default, the name of the task stack required for all activity is the app's package name. Of course this is not absolute, we can also artificially set the "cannot be consistent with the package name." The task stack is divided into the foreground task stack and the background task stack, the activity in the background task stack is paused, and the user can switch back to the foreground by switching the background task stack.

Here we discuss an interesting question to deepen our understanding of singletask.
Suppose there are 3 activity a B c;a are ingress activity, the schema is standard, and B and C are singletask patterns, and they specify the same Affinaty property. Now come the boot order: A->b->c->a->b, the last two consecutive press back key, then what is the situation? You can think for a moment.

The answer is back to the desktop. Why is it? Here's an explanation.

A starts B, and B is the singletask mode, so it creates a task stack named Affinaty and then creates an instance of B into the new task stack, and B starts C, because C is also the Singletask mode, but the task stack it needs is already " B and C have the same affinaty attribute ", then just create an instance of C directly into the top of the task stack where B is located. Then C started a, because a is the standard mode, then is who launches it on whose stack, in other words a also put to B where the stack top. Now, there are two stacks, one is the default task stack named Package name, there is only a, there is a named Affinaty task stack, there is a BCA. Then A and B, because B is singletask,b need to go back to the stack top of the task stack, then the AC must be out of the stack. Then there is only B in the task stack. Then press back,b out of the stack, then b where the task stack does not exist, this time can only be back to the background task stack and a display. If you press back again, you will return to the desktop.

1.2.2 Activity's Flags

You should all know that there are two ways to specify the activity's startup mode, one to configure in the configuration file, and one to set the flag bit in the intent. There are several common sign-bits:
Flag_activity_new_task: Specify Singletask mode
Flag_activity_single_top: Specify Singletop mode
Falg_activity_clear_top: An activity with this tag that, when it starts, stacks up all the activity instances that are on it in the same task stack.
Flag_activity_exclude_from_recents: Activity with this tag does not appear in the list of historical activity, This tag is useful when in some cases we don't want users to fall back to our activity through the history list.

Matching rules for 1.3 intentfilter

As you all know, when you start the activity, the implicit invocation requires intent to match the filtering information set in the Intentfilter of the target component, and if the mismatch does not start the target activity. The filtering information in Intentfilter is Action,category,data.
To match the filter list, you need to match the Action,category,data information in the filter list at the same time. Otherwise, the match will fail. A filter list of action,category and data can have multiple, all action,category and data constitute a different category, the same class of information together constrain the current category of matching process, only one intent match the action category , the category and data categories match exactly, and only the exact match will successfully start the target activity. On the other hand, there can be multiple intent-filter in an activity, and a intent can successfully initiate the corresponding activity as long as it matches exactly any set of intent-filter.

The following is a simple analysis of the matching rules for various attributes.

Matching rules for 1.3.1 action

The action is a string, the system has predefined actions, and we can define our own action in the app.
Intent how to test the action:
The 1>intent can contain only 1 action.
More than one action can be configured in 2>intent-filter.
3> if the action of the intent object is configured in Intent-filter
Action Declaration, the action test succeeds.
4> If the intent object does not contain an action, the default match fails

Matching rules for 1.3.2 category

Category is a string and the system has predefined category, and we can define our category in the app.
The 1> Intent object can contain multiple category
Multiple category can be declared in 2> Intent-filter
3> If the intent object contains all the category and Intent-filter
The category is the same category as declared in the
The test was successful.
4> If the category is not included in the intent, you can pass all
The category of the test.
5> If you want an activity to be able to receive implicit calls, you must specify "Android.intent.category.DEFAULT" in the Intent-filter The system will add Android.intent.category.DEFAULT "This category" by default when the activity is started.

Matching rules for 1.3.3 data

Data consists of two parts, MimeType and URIs. MimeType refers to the media type, such as Image/jpeg, and the URI contains more data.
Here is the structure of the URI:
://:/[||]
Example: content://com.example.project:200/folder/subfolder/etc
Http://www.baidu.com:80/search/info

Scheme:uri mode, such as http,file,content, if no scheme is specified in the URI, then the other parameters of the entire URI are invalid. This also means that the URI is invalid.
The hostname of the Host:uri, such as www.baidu.com, if the host is unspecified, the other parameters of the entire URI are also invalid, which means that the URI is invalid.
Port number in Port:uri, port is meaningful only if scheme and host are specified in the URI.

After the data format is introduced, let's take a look at the matching rules of data.
Intent test of the data
The 1> Intent object can contain 1 specific data (URIs)
2> Intent-filter defines what the current activity can handle
The format requirements for the data.

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

The effect of both is to indicate that this is an entry activity and will appear in the list of applications in the system.
First case: There is main, no launcher, no icon in the program list
Cause: Android.intent.category.LAUNCHER Determines whether the application appears in the program list
Second case: No main, launcher, no icon in the program list
Reason: Android.intent.action.MAIN determines the activity that the application starts first, if there is no main, then does not know which activity to start, therefore does not have the icon to appear

This chapter is about the same thing. I've seen it two times before I'm going to start writing notes.

1th Chapter Activtiy life cycle and 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.