Some of the personal summary of activity, more scattered.

Source: Internet
Author: User
I. Introduction of activity
1. What is activity.
First look at the definition of activity on the Google Android Developer website: Activity is an app component that users can interact with to perform actions such as making a call, taking a photo, sending an email, or viewing a map. Each Activity will have a window for drawing its user interface. Windows are usually filled with screens, but they can be smaller than the screen and float on top of other windows.
In layman's terms, activity is a component that can contain a user interface, and an application can contain 0 or more activity (with 0 applications, which is rarely seen in applications that are not visible), One activity is typically specified as a mainactivity, and each activity can start another activity. Activity is a user interface program that provides users with an interactive interface function that is the basic functional unit of the activity application.
2. How to create an activity.
Similarly, a more detailed explanation has been made on the developer's Web site: To create an activity, you must create a subclass of activity (or use its existing child classes). You need to implement callback methods in a subclass that are called by the system when the activity transitions between various states of its life cycle, such as creating activity, stopping activity, recovering activity, or destroying activity. The two most important callback methods are:
OnCreate ()
You must implement this method. The system calls this method when it creates your Activity. You should initialize the required components of the Activity within the implementation. Most importantly, you must call Setcontentview () within this method to define the layout of the Activity user interface.
OnPause ()
The system calls this method as the first signal that the user leaves the activity (but does not always mean that the activity will be destroyed). You should typically confirm any changes that are still valid after the end of the current user session in this method (because the user may not return).
From the above explanations, we can see three points: a. To create an activity, you first need to create a subclass of the activity (that is, create the class and extends the activity). When the b.activity is created, the first call is the OnCreate () method, and when the user leaves the activity, the OnPause () method is called [the specific two callback methods will be explained in detail in the next chapter's life cycle]. C.activity itself does not have an interface for display, it just creates a window [the window is usually filled with the screen or can be smaller than the screen and floats on top of the other interface], and the developer calls Setcontentview within the important callback method oncreate () method of the activity. () method to display the user interface.
The Setcontentview () method mentioned above requires an. xml file, so our interface layout for the activity needs to be written to the Setcontentview () called in OnCreate () in this activity In a consistent XML file, such that the interface element one by one that you want to display is displayed in the user interface after the activity is created. And the simple XML is Extensible Markup language and the specific situation can be seen here, it is described in detail and there are examples of {http://blog.csdn.net/fengbingchun/article/details/38978591}
Several ways to load 3.xml files
As mentioned above, we can lay out the interface elements that the activity displays in the XML file, so how to load the XML file into the activity becomes the most important issue. In general, there are several ways to implement loading.
①setcontentview (), this load is typically used in the activity's Oncreat () method to load the app's layout content display and caption display. That is, it loads two parts, one is the title part, the other is the content part.
②layoutinflater instantiated objects, through the inflate () method can get the layout file, this gets the layout file and Findviewbyid () in a different way, the inflate () method is to get the XML format file in Res/layout, It also returns the View object, allowing us to add the layout file dynamically. Findviewbyid (This is a way to get a control from an ID in a layout, and you can also get a layout control.)
③ inherits the Preferenceactivity class load XML file, using method Addpreferencesfromresource (r.xml.preferences) to load the XML file.
The ④ layout uses the <include> tag, which is to load the layout from another XML in one XML file, and the method that loads the XML into the activity to display can use either of the methods described above.
After we load the XML file into activity ready for display, we need to do the most important step of declaring this activity in manifest.
4. Declare activity in manifest
Manifest belongs to the Androidmanifest.xml file, which contains all the information about your app [http://my.oschina.net/weiCloudS/blog/367709 This is a detailed introduction to the Androidmanifest file], So the activity that you create needs to be declared in the Androidmanifest.xml file to ensure that all the information that your app has before it runs is understood by the system to make it easier to display what you want to show. The specific way to declare it is as follows:
<manifest ... >
<application ... >
<activity android:name= ". Exampleactivity "/>
...
</application ... >
...
</manifest >
That's it. An activity has been created, and you can see your own defined interface after you run it in the IDE.
5. Detailed description of the Androidmanifest file
A androidmanifest.xml file must be included in the root directory of each app (and the file name is accurate). The manifest file provides the Android system with basic information about your app that the system must obtain to run any application code. In addition, the manifest file can perform the following actions:
• Name the Java package for your application. The package name acts as a unique identifier for the app
• Describe the various components of your app: Activity, service, broadcast sink, and content provider that make up your app. Name and publish the functionality of each component's class (for example, Intent messages that they can handle). According to these statements, the Android system can understand what this component is, and under what conditions they can be started
• Identify the processes that will host the application components
• Declare what permissions your app must have to access protected portions of the API and interact with other apps
• Also declares the permissions that other apps need to interact with the app component
• Lists the instrumentation classes that provide analysis and other information while the app is running. These statements will only appear in the manifest file when the app is in the development and testing phase, and they will be deleted before the app is published
• Declare the minimum Android API level required for your app
• List the libraries that the app must link to
In general, the structure of the Androidmanifest file is as follows [all elements already included]:
<?xml version= "1.0" encoding= "Utf-8"?>

<manifest>

<uses-permission/>
<permission/>
<permission-tree/>
<permission-group/>
<instrumentation/>
<uses-sdk/>
<uses-configuration/>
<uses-feature/>
<supports-screens/>
<compatible-screens/>
<supports-gl-texture/>

<application>

<activity>
<intent-filter>
<action/>
<category/>
<data/>
</intent-filter>
<meta-data/>
</activity>

<activity-alias>
<intent-filter> ... </intent-filter>
<meta-data/>
</activity-alias>

<service>
<intent-filter> ... </intent-filter>
<meta-data/>
</service>

<receiver>
<intent-filter> ... </intent-filter>
<meta-data/>
</receiver>

<provider>
<grant-uri-permission/>
<meta-data/>
<path-permission/>
</provider>

<uses-library/>

</application>

</manifest>
Only <manifest> and <application> are required in the Androidmanifest file and can occur only once, and most of the remaining elements may appear multiple times or not. The order in which elements of the same level appear is not in any format, but <activity-alias> must follow the <activity> referred to by the alias. And in the course of programming we can borrow one or part of the above elements to achieve the functions and requirements that we need to implement. Detailed explanations also require hands-on programming to experience and understand how they work. We'll explain only a few of them here.
①action: Action tag, present in the intent-filter tag, if bound to an activity, can indicate that the activity has that action, if there is an intention to emit, and with such an activity defined action, then, It is possible to locate the activity, which is generally used in conjunction with the category. eg

②activity: Activity tags, define a number of properties to set some of the activity's characteristics, such as: Android:configchanges, Android:label, Android:launchmode, etc., The detailed contents of these properties can be viewed in the official documentation.
③activity-alias: An active tag replacement, typically used to set an alias for an activity, the most important attribute of which is android:targetactivity, which sets the activity to point to.
④application: Application declaration, with a large number of attributes, and activity, Service, receiver are defined inside this tag, and can also be a similar to the global configuration role, such as setting a theme.
⑤intent-filter: The intent filter, which defines the intent that the Activity,service or broadcast can receive, must contain the action tag.
⑥meta-data: Metadata tags that define the data that some systems can use. However, you must define a unique name for the metadata.
⑦manifest: The main Configuration tab, similar to the 6. How to activate activity.
We already have an activity with interface elements in the two steps above, and the next step is to get the activity started. Normally when we start mainactivity, we just need to run your app in the IDE and you can see it on a virtual machine or device, but in general an application is always composed of multiple activity loosely coupled This requires that we be able to jump from mainactivity or any activity to the desired activity. There are generally three different ways to start an activity when you start the activity:
① display Start-up: In layman's terms, the code is a straightforward way to start an activity. The code is as follows:
Intent Intent = new Intent (this, signinactivity.class);
StartActivity (Intent);
② implicit startup: Contrary to the display start, popularly speaking is not so directly start an activity, but by adding inten-filter in the manifest file, and then start the intent in the code. The code is as follows:
Configuration in manifest:
Activation in activity:

③ Set alias start: This startup is mainly in the Activity tab to set the Activity-alias tag, and set Intent-filter, when running to the emulator or the real machine will generate two portal icon, one is the original activity of the entrance, The other is the entry after the alias is set.
7. How to end activity.
After starting the activity, we can't always turn it on, which can take up a large part of the memory resources, so we need to say that the active activity ends at the right time. You can end the activity by invoking the activity's finish () method. You can also end another Activity that you started by calling Finishactivity (). {However, in general, this method is not recommended to end the activity directly, it should be done in the corresponding callback method in the activity's life cycle described below.}
8.Intent and Intentfilter Introduction
Intent is responsible for the operation of the action, the action involved in data, additional data description, Android based on this intent description, is responsible for finding the corresponding component, the intent passed to the calling component, and complete the call of the component. As a result, intent plays a role as a media intermediary that specifically provides information about the components that are called to each other, enabling decoupling between the caller and the callee. In the application, we can use intent in two ways:
Direct intent: Specifies the intent of the component attribute (called SetComponent (componentname) or SetClass (Context, Class). Notifies the app to launch the corresponding component by specifying a specific component class.
Indirect intent: No intent is specified for the component property. These intent need to contain enough information so that the system can determine the components that meet this intent in all available components, based on this information.
For direct intent,android There is no need to parse because the target component is already clear.
What Android needs to parse is those indirect intent that, through parsing, map intent to activity, intentreceiver, or service that can handle this intent. The intent parsing mechanism is primarily to find a matching intent by locating all intentfilter in the androidmanifest.xml and the intent defined therein.
Intent Filter describes what kind of Intent objects a component is willing to receive, and Android abstracts it into a Android.content.IntentFilter class. In Android's androidmanifest.xml configuration file, you can specify its intent filter for an activity via the <intent-filter > node to tell the system what type of activity it can respond to The Intent.
When you use StartActivity (intent) to start another Activity, if you specify the Component property of the intent object directly, Activity Manager will attempt to start the Act specified by its Component property Ivity. Otherwise, Android will find the most matching boot from all the activity installed in the system via the other properties of Intent, and the application will get an exception thrown by the system if no suitable activity is found.
9. How to determine whether the activity or the control.
When we are not sure, we need to find a way to verify, here is mainly to introduce the method of validation.
① using the Hierarchyview tool, the tool will show the activity or control that the root phone is running
② uses the grep "keyword"-inrs./command. Locate the keyword on the interface to locate the specific class.
In short, when we determine what code is displayed, it is clear that the control or activity is.
Second, activity life cycle
1. Life Cycle Introduction
The life cycle, literally, can seem to have the most impact on activity, so the life cycle of learning is the most important part of the whole activity learning. Overall activity has a total life cycle of 7, namely: OnCreate (), OnStart (), Onresume (), OnPause (), OnStop (), OnDestroy (), Onrestart (). The specific life cycle flow is shown in Figure 2.1. It can be seen that in addition to Onrestart () The life cycle is 22-relative. So in the memory and learning time can be 22 to each other than the opposite of learning.
2.onCreate ()
This method is overridden in each activity, and it is invoked the first time the activity is created, and all normal static settings should be performed in this method-creating the view, binding the data to the list, and so on. The system passes a Bundle object to this method that contains the previous state of the Activity, but only if the state is captured, always followed by OnStart ().
3.onStart ()
Called before the Activity is about to be visible to the user. If activity is transferred to the foreground, then Onresume () is followed by OnStop () if the activity goes into a hidden state.
4.onResume ()
Called before the Activity is about to start interacting with the user. At this point, the activity is at the top level of the activity stack and has user input focus.
Always followed by OnPause ().
5.onPause ()
Called when the system is about to start another Activity. This method is typically used to confirm unsaved changes to persistent data, stop animations, and other content that might consume the CPU, and so on. It should perform the required action very quickly, because the next Activity will continue after it returns.
If activity returns to the foreground, then Onresume () is followed by OnStop () if the activity is transferred to the invisible state of the user.
6.onStop ()
The Activity is called when the user is no longer visible. This can happen if the activity is destroyed, or if another activity (an existing activity or new activity) continues to execute and overwrite it. If activity resumes interaction with the user, then Onrestart () is followed, and if the activity is destroyed, then OnDestroy () is followed.
7.onDestroy ()
Called before the Activity is destroyed. This is the last call the Activity will receive. It may be called when activity ends (someone invokes finish () on activity), or the system temporarily destroys the activity instance to save space. You can differentiate between the two scenarios by using the Isfinishing () method.
8.onRestart ()
Called before the Activity has stopped and is about to start again. Always followed by OnStart ()
Three lifetimes of 9.Activity
In the first section of this chapter, it has been said that the life cycle of activity is basically 22 corresponding, so it can be divided into three stages: A, full lifetime: That is, between OnCreate () and OnDestroy () is the complete survival period, In general, the activity completes all initialization in OnCreate () and completes the memory release in OnDestroy (). B, visible lifetime: The experience between OnStart () and OnStop () is the visible lifetime, during which the entire activity is visible to the user, even if it is sometimes impossible to interact with the user. We can use this feature to develop more space-saving activity, such as loading resources in OnStart (), freeing resources in OnStop (), and saving activity from consuming too much resources in the process of stopping. C, foreground survival: that is, the activity between Onresume () and Onpasue () is the foreground life, activity is always active, during which activity is always interacting with the user, usually the most contact is the activity during this state.
10.Activity State Save
Normally, when activity is paused or stopped, the status of the activity is preserved. Because when activity pauses or stops, the activity object remains in memory-all information about its members and the current state is still active. As a result, any changes that the user makes within the activity are retained so that the changes persist when the activity returns to the foreground (when it "continues").
However, when the activity enters a paused or stopped state, the system does not have enough memory to destroy the activity of this state, and the activity object is destroyed, and when the user returns to activity, the system cannot save its intact state to return the activity. Only the activity object can be recreated, but for the user, he may think that this activity has nothing to do with it, in which case the Onsaveinstancestate () method is required to save the state information about the activity to ensure Important information about the Activity state is preserved. The system calls Onsaveinstancestate () before the Activity becomes easy to destroy. This method is passed a Bundle in which 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 the application process and the user returns to the activity, the activity is rebuilt and the bundle is passed to both 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). Figure 2.2 shows the method that needs to be implemented when the activity is not visible and is killed and returned back and directly restart the activity.

Figure 2.2:activity The process of interrupt, resume, kill-back
11. Transformation of activity life cycle when the screen is switched
The best way to learn the call order and call timing of the learning lifecycle is to rewrite the seven callback methods in which the log output is best viewed in logcat, so we'll show you the log output of the activity life cycle when switching between the two screens.
You can see that the full life cycle is called again each time the screen is toggled, which is equivalent to recreating the activity. This results in the loss of data due to the fact that sometimes the data in the activity can be lost as a result of the switching between the screen and the monitor, but the user experience is reduced, but it is shown from the graph that the Onsaveinstancestate () method is always called before activity is not visible on each switch. , and the Onrestoreinstancestate () method is called before the activity is re-visible, so the Onsaveinstancestate () method can be used to save some activity state information, data information, etc. The Onrestoreinstancestate () method is used to restore the activity status information, data information and so on to improve the user experience.
You can also fix the activity as a horizontal or vertical screen by setting it, and you won't have the life-cycle effect when you switch the screen vertically. The following two ways can be set: A. Set directly through the Android:screenorientation property in the master configuration manifest. B. by Setrequestedorientation (Activityinfo.screen_orientation_landscape) in the OnCreate () method, or Setrequestedorientation ( activityinfo.screen_orientation_portrait); to set.
You can also add android:configchanges= "orientation|keyboardhidden|screensize" to the Activity tab in the manifest file if you have to switch between the screen and the bottom. property to control. In this attribute orientation represents the direction of gravity, keyboardhidden means that the input keyboard is hidden and screensize is adapted to the entire screen.
Note: When setting the Android:configchanges property, Google gives us a total of 13 values to make the settings we need. When set, these 13 values can be set together, just in the middle with the "|" Can be separated, such as: android:configchanges= "mcc|mnc|locale|touchscreen|keyboard|keyboardhidden|navigation|screenlayout| Fontscale|uimode|orientation|screensize|smallestscreensize "For these 13-valued official online specific explanations are as follows:

Call of 12.finish ()
This method of finish () has been mentioned in the previous article. The main function is to end the activity. But there is also a way to end activity in the activity life cycle, this section is mainly about the activity life cycle after calling the finish method in a method of the activity's life cycle.
①oncreate ():
Log

②onstart ():
Log

③onresume:
Log

④onpause:
Log

⑤onstop:
Log

⑥ondestroy:
Log

⑦onrestart:
Log

⑧onrestoreintancestate:
Log

⑨onsavedinstancestate:
Log

The entire log shows that the life cycle is 22 reciprocal, such as performing finish in OnCreate, only OnDestroy is executed, and finish in OnStart, only OnStop and OnDestroy are executed. From this we can see that there must be first, after the implementation of the first life cycle of the method, the corresponding life-cycle method must be executed. However, the two methods of onsavedinstancestate and onrestoreintancestate do not correspond exactly, because these two methods are used to save the activity state and the recovery state of the method, It is important to note that Onrestoreintancestate will only perform this method when switching between the two screens.
OnDestroy () method is also the role of destroying activity, so in the OnDestroy call the finish method should be aware of the first to determine whether the current activity has been destroy off, otherwise under certain conditions will be an error.
Third, the communication between the activity, the stack type management
Passing messages between 1.Activity
In the first chapter, the Startactivityforresult () method is briefly introduced to transfer the messages between the activity. But sometimes the activity instance that we need to deliver the message may run in a different process, so when the message is delivered, it is necessary to pass the message through the Intent object, which is represented by the Intent object in Android, a Intent The object contains not only the destination of the message, but also the contents of the message. The destination is required for this intent object, and the content is optional. The detailed introduction and use of intent has been introduced in the first chapter, here is not to repeat.
2.Activity on-the-stack management

In the above, I have mentioned the stack of this thing. In short, the stack is an advanced data structure [about the stack of detailed introduction can be searched under the "data structure of the stack in the introduction" to understand the next]. I've already said in the beginning that an app can have multiple activity components, and on Android, it's a stack to manage a lot of activity. That is, at some point, only one activity is at the top of the stack, that is, only one activity can interact with the user, and only when the activity is suspended or destroyed will the activity below be able to float to the top of the stack, Or if a new activity is created, the old activity is pushed down by the stack. Activity is the performance layer of the Android program. Each display screen of a program is an activity. The activity that is running is at the top of the stack and it is in the running state. It can also be seen from this diagram that the activity is extremely easy to kill when inactive, the color of the above image indicates the probability of being killed, the more at the bottom of the stack is more likely to be killed, but the specific situation and the memory state of the device.
Iv. activation mode and usage of activity
Sometimes in projects we need to specify the appropriate startup mode for the activity based on special needs. The boot mode is divided into four categories, Standard, Singletop, Singletask, and singleinstance, which can be set in the main configuration manifest file <activity> tag under Android: Launchmode to select the startup mode. The startup mode is standard by default.
1.standard
As the default startup mode, it is simply that each time you start an activity in this mode, a new instance is created and is placed on top of the stack.
2.SingleTop
When the startup mode is Singletop, whenever the activity is started, if it is found that the top of the stack is already the activity is directly using this instance, if the top of the stack is not the same activity re-create the instance, and placed in the top of the stack.
3.SingleTask
When the startup mode is Singletask, each time the activity is started, the system first checks the stack for the presence of an instance of the activity, uses the instance directly if it exists, and then stacks all the activity on top of the activity, and creates a new instance if it does not exist.
4.SingleInstance
SingleInstance This startup mode is the most complex mode, when you start activity in singleinstance mode, a new stack is enabled to manage the activity, which makes it possible for any other program to access will be shared with the same stack for processing, it will be possible to share the function of the activity instance.
Note: Sharing in singleinstance mode is a prerequisite for all activity not being destroyed.

=============================================================================================================== =====================

Some of the content in the middle is referenced from other blogs, and was not written in time to indicate the source. My mistake. Some of the log pictures I do not know how to upload. I'll use this later, and then update this document. Share.

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.