"Activity"
An activity is an application component that provides a screen that users can use to interact in order to accomplish a task, such as dialing, taking photos, sending emails, and looking at a map. Each activity is given a window in which the user interface can be drawn. Windows are usually filled with screens, but they can also be smaller than the screen and float on top of other windows.
An application is usually composed of multiple activities, usually loosely coupled relationships. Typically, an activity in an application is designated as the "main" activity, the activity that is presented to the user the first time the application is started. Each activity can then be activated by another action in order to accomplish different actions. Each time an activity starts, the previous activity stops, but the system retains the activity on one stack ("Back stack"). When a new activity starts, it is pushed to the top of the stack to get the user focus. The back stack conforms to the simple "LIFO" principle, so when the user completes the current activity and then clicks the return button, it is ejected from the stack (and destroyed) before the activity resumes.
When an activity stops because of a new activity initiation, it is notified that the state transition passes through the activity's lifecycle callback function. There are many callback functions where an activity may be received, originating from its own state change-whether the system creates it, stops it, restores it, destroys it-and each callback provides you with the opportunity to complete a designated job that fits the state. For example, when you stop, your activity should release any large objects, such as a network database connection. When the activity resumes, you can regain the necessary resources and resume the interrupted action. These state transitions are part of the life cycle of an activity.
"creatingan activity"
To create an activity, you must create a subclass of the activity (or subclass of an activity). In your subclass, you need to implement a callback method for the system callback, when the activity is converted in multiple states of its lifecycle, such as when the activity is created, stopped, restored, or destroyed. The two most important callback methods are:
OnCreate ()
You must implement this method. The system calls it when creating your activity. In your implementation, you should initialize the basic components of your activity. More importantly, this is where you have to call Setcontentview () to define the activity user interface.
OnPause ()
The system calls this method when the user leaves your activity (although not always means the activity is destroyed). This is usually where you should submit any changes, which will go beyond user session (because the user may not be back again).
There are several other lifecycle callback functions you should use in order to provide a fluent user experience, and the abnormal interruption of table operation will cause your activity to be interrupted or even destroyed.
1, Implementing a user interface
The user interface for an activity is provided by a hierarchical view--an object that inherits from the view class. Each view controls a specific rectangular area in the activity window and responds to user interaction. For example, a view might be a button that initializes the action when the user touches it.
Android offers a lot of predefined view that you can use to design and component your layout. "Widgets" is a view that provides a visual (and interactive) element to a screen, such as a button, a file field, a check box, or just an image. "Layouts" is inherited from ViewGroup view, providing a special layout model for its child view, such as thread layout, lattice layout, or dependency layout. You can subclass view and ViewGroup classes (or existing subclasses) to create your own widgets and just and apply them to your activity layout.
The most common approach is to define a layout using view plus an XML layout file to keep in your program resources. In this way, you can maintain your user interface design independently of the code that defines the activity behavior. You can set the layout to use Setcontentview () as the UI, passing resource IDs for the resources layout. However, you can also create new views in your activity code, and create a view hierarchy by inserting new views into ViewGroup, and then using that layout by passing to the root ViewGroup to Setcontentview ().
"declaringthe activity in the manifest"
You must declare your activity in the manifest file in order for it to be accessible by the system. To declare your activity, open your manifest file and add a <activity> element as a child element of the <application> element. For example:
"Using Intent Filters"
A <activity> element can also specify a variety of intent filters--use <inetent-filter> elements--in order to declare that other applications can activate it.
When you create a new application using the Android SDK tool, stub activity is automatically created for you, containing a intent filter, stating that the activities respond to the "main" action and should be placed in the "launcher" category. Intent filter looks like this.
<action> element Specifies that this is a "main" entry point for this application. The <category> element specifies that the activity should be included in the list of system applications (in order to allow the user to initiate the activity).
If you want your application to be self-contained and do not want other applications to activate its activities, then you do not need any other intent filters. Only one activity should have a "main" action and a "launcher" category, just as in the previous example. You do not want to be accessed by other applications the original activities should have no intent filters and you can launch them through their own display intent.
However, if you want your activity to respond to a shadow containing intents from other applications (and your own), then you must define additional intent filters for this activity. For each type of intent you want to respond to, you must include a <intent-filter>, a <action> element, an optional, a <category> element, and/or a <data> element. These elements specify the type of intent that your activity can respond to.
"startingan activity"
You can open another activity through startactivity (), passing a intent describing the activity you want to start. Intent specifies either the activity you want to start or describe the action you want to complete (the operating system chooses the appropriate activities for you, possibly from a different application). A intent can transmit small amounts of data to be activated by the activity used.
Completely working within your application, you will often need to simply start an unknown activity. You can do this by creating a intent display definition of the activity you want to start, using the class name. For example, the following shows how an activity can start another activity named Signinactivity:
However, your application may want to perform some action, such as sending a message, a file message, or a status update, using data from your activity. In this case, your application may not have its own activity to complete the action, so you can motivate the activity provided by other applications on the device to perform your action. This is where intent really counts-you can create a intent describe the action you want to perform, and then the system starts a suitable activity from another application. If there are multiple activities that can handle this intent, then the user can choose which one to perform. For example, if you want to allow users to send mail, you can create the following intent:
Extra_email additional add to intent an array of strings to specify an email address, and when a mail application responds to the intent, it reads the string array and places them in the corresponding field. In this case, the activity of the email application starts and when the user finishes, your activity resumes.
"startingan activity for a"
Sometimes you may want to receive an activity that results from your initiation. In this case, the activity is opened through Startactivityforresult () (instead of startactivity ()). The result is then received from the subsequent activity, implementing the Onactiviryresult () callback function. When the subsequent activity completes, it returns a result to your Onactivityresult () function through a intent.
For example, you might want the user to select one of their contacts, so your activity can do something with the contact person. Here is how you create such a intent and operation result:
This example shows the basic logic you should use in your Onactivityresult () function, in order to manipulate the results of an activity. The first condition detects whether the request is successful-if so, then ResultCode will be result_ok--and whether the request is the response is ringing know-in this case, Requestcode matches the parameters of the second parameter with Startactivityforresult (). There, the code operates the result of the activity by querying the data returned in intent.
What will happen is that a Contentresolver implementation query content provider, returns a cursor allow read query data.
"shutdown a activity"
You can close an activity by calling its own finish () method. You can also close an independent activity you previously initiated via Finiactivity ().
Note: In most cases, you should not display the results of an activity using these methods. As discussed below on the lifecycle of activity, the Android system manages the lifecycle of an activity for you, so you don't need to result in your own activity. Calling these functions is harmful to the user experience and only if you do not want the user to return to the activity.
"managingThe Activity Lifecycle"
Managing the lifecycle of your activity is critical to developing a robust and resilient application by implementing a callback function. The life cycle of an activity is directly affected by other activity associated with it, task and bask stack.
An activity can exist in the main three states:
1, resumed
The activity is in the foreground and has user focus. (This state is sometimes called "running")
2, paused
Another activity is in the foreground and has the user focus, but this is still visible. That is, another activity is visible above this, and the current activity is partially transparent or does not cover the entire screen. A paused activity is completely alive (the Activities object dimension is in memory, it maintains all state and memory information, still connects to the window manager), but can be killed by the system in situations where memory is extremely needed.
3, Stopped
One activity is completely blocked by another activity (the activity is now in the background). A stopped activity is still alive (activities object is maintained in memory, it expands all state and member information, but does not bind the window manager). However, it is no longer visible to the user and can be destroyed by the system where it is needed.
If an activity paused or stopped, the system can discard it from memory by requiring it to end (call its finish () method), or simply kill its process. When the activity is opened again (after being finished or killed), it builds everything again.
"Implementing the Lifecycle Callbacks"
When an activity converts to or transforms the state mentioned above, it is notified by various callback functions. All of these callback functions are hooks, and you can override them to do the right job when your activity state changes. The following activity skeleton contains each of the basic lifecycle functions:
Note: Your implementation of these lifecycle functions must invoke the implementation of the parent class before you do your own work, as shown above.
Together, these functions define the entire lifecycle about an activity. By implementing these methods, you can monitor three nested loops in the activity lifecycle.
1. The entire life time of an activity occurs in the OnCreate () and OnDestroy () functions. your activity should set the global state (for example, define the layout) at OnCreate () and release all resources in OnDestroy (). For example, if your activity has a thread running in the background to download data from the network, it may create that thread at OnCreate () then stop the thread in OnDestroy ().
2. A visual life cycle occurs between OnStart () and OnStop (). during this time, the user can see the activity on the screen and interact with it. For example, OnStop () is tuned when a new activity begins and this is no longer visible. Between these two functions, you can maintain resources that need to be used to show activity to the user. For example, you can register a broadcastreceiver in OnStart () and then log off at OnStop () when the user no longer sees what you are displaying. The system may tune OnStart (0 and OnStop () multiple times during this entire lifeline, when the activity is converted between visible and invisible.
3. The foreground life period of an activity occurs between onresume () and OnPause (). During this period, this activity is on the screen above all other activity and has user focus. An activity can often be converted into and transformed out of the foreground-for example, OnPause is called when the device is ready to Hibernate su when a dialog box is generated. Because this state can be converted frequently, the code should be lightweight in both states in order to avoid slowing down the conversion speed so that the user waits.
Image 1 states these loops and shows a state transition path where an activity can occur. The rectangle represents the callback function you can implement.
Figure 1. The activity lifecycle.
The same lifecycle callback function is listed in Table 1, which describes in more detail the callback function to place each life cycle in the activity, including whether the system can kill the event after the callback function completes.
Table 1. A Summary of the activity lifecycle ' s callback methods.
Since OnPause () the first of their three, a quantity activity is established, OnPause () is the last method guaranteed to be invoked-if the system must be restored within a state of emergency, then OnStop () and OnDestroy () may not be invoked. Therefore, you should use OnPause () to write the storage of the data (for example, edit). However, you should carefully select which information must be retained in the OnPause (), because any blocking operations in this function block to the next activity's conversion thus reducing the user experience.
Saving activity State "
" This article simply mentions what an activity is paused and stopped, The state of the activity was maintained. This is true because the activity object is still in memory when it is paused or stopped--all the information about its member variables and the current state exists. As a result, any user changes are maintained in memory in the activity, so when the activity returns to the foreground (resumes), these changes still exist.
However, when the system destroys an activity in order to restore memory, the activity object is destroyed, so the system cannot simply resume it in full state. Instead, the system must create an Activity object if the user browses back to it. That is, the user does not know that the system destroys the activity and then creates it, so that the activity is the one that it just had. In this case, you can determine the important information about the state of the activity being retained by implementing an additional callback function that allows you to save information about your activity and then restore it when the system is recreated.
This callback function where you can save the current state information is onsaveinstancestate (). The system tuned this function before destroying the activity, and passing a bundle object. Bundle is where you can have state information, using Name-value pairs, using methods such as putstring (). Then, if the system kills your activity process and the user browses back to your activity, the system passes bundle to OnCreate so you can restore the status of the activity you saved at Onsaveinnstancestate (). If no information is saved, the bundle passed to OnCreate () is null.
Note: There is no guarantee that the onsaveinstancestate () will be invoked before your activity is destroyed because there is no need to store the situation (for example, when the user leaves your activity, the user displays the end). If this method is invoked, it is always before the OnStop () and the probability is before the OnPause ().
However, even if you do not do anything and do not realize onsaveinstancestate (), some of the activity's state is restored by the default onsaveinstancestate of the active class. In particular, the default view's onsaveinstance () in terms of layout allows each view to provide its own information to be saved. Almost all of the widgets in the Android framework implement this method properly, so any visible changes to the UI are saved and restored when your activity is created. For example, the EditText widget saves any text that is entered by the user, and the checkbox widget is checked or unchecked. The only job you need is to provide a unique ID (through the Android:id attribute) to each widget that you want to save the state. If a widget has no ID, it does not save its state.
Although the default implementation of Onsaveinstancestate () holds very useful information about your activity UI you will still need to overwrite it to save additional information. For example, you may need to save the variables that change during the activity life (and the data that is stored in the UI, but the variable that holds the UI values is not saved by default).
Because the default onsaveinstancestate () helps you save UI state, if you override these methods in order to save additional information, you should call the implementation of the parent class each time about Onsaveinstanstate () before doing the work.
Note: Since Onsaveinstancestate () is not guaranteed to be invoked, you should use it only to record temporary states on your activity--you should never use it to store permanent data. Instead, you should use OnPause () to store permanent data (such as data stored in a database) when the user leaves the activity.
A good way to test your program's ability to save state is to simply convert the device to change the screen direction. When the screen direction changes, the system destroys and rebuilds the activity in order to apply the optional resources for the new direction. For this reason, your activity restores its state when it is created very important because the user usually transforms the screen when using the application.
"Handling Configuratinon changes"
Some device configurations can be changed at run time (for example, screen orientation, keyboard availability, and language). When such a change occurs, Android restarts the running Activity (OnDestroy () is invoked and then OnCreate () is invoked). The restart behavior is designed to help the application adapt to the new configuration by automatically loading your application through optional resources that you provide. If you set up your activity appropriately to manipulate this event, it will be more resilient to unpredictable events in the lifecycle.
The best way to manipulate configuration changes, such as screen orientation, is simply to predefined the state of your application using Onsaveinstancestate () and Onrestoreinstancestate () (or OnCreate ()), as discussed earlier.
"Coordinating activities"
When one activity starts another, they all experience life cycle transformations. The first activitypauses and stop (although, it will not stop if he is still visible in the foreground), another activity is created. In case these activities data are saved to disk or wherever, it is important that the first activity does not exit before another starts. Quite the case is that the latter process starts overwriting the previous stop time.
The
Life cycle callback is well defined, especially when two activities are in the same process, and one of them starts another. The following is the order of operations when activity a initiates the execution of the action B:
1, OnPause ().
2, Activity B's OnCreate (), OnStart (), and Onresume () methods are executed, in sequence. (b now has user focus)
3, if a is no longer visible, its OnStop () method executes.
This life-cycle function call sequence allows you to transform information from one activity to another. For example, if you have to write to a database, when the first activity stops so that the next activity can read it, then you should write to the database at OnPause () instead of OnStop ().