"Go" Android Development Tour: Component life cycle

Source: Internet
Author: User
Tags hosting

Component life cycle (i) Introduction

Application components have a life cycle--the first time Android instantiates their response intent until the end of the instance is destroyed. During this time, they are sometimes active, sometimes inactive, and sometimes visible to the user for the activity, sometimes invisible. The component life cycle discusses the life cycle of activities, services, and broadcast receivers-including their possible state during the life cycle, methods for notifying state changes, and the possibility of the process of hosting the components of those States being terminated and instances being destroyed.

This article focuses on the life cycle of activities and their possible status, and how the notification state changes. is divided into the following three parts:

    • 1. Activity life cycle
    • 2. Save Activity Status
    • 3. Coordination activities
1. Activity life cycle

There are three basic states of an activity:

    • Active or running , it runs in the foreground of the screen (at the top of the current task's activity stack). This activity has the focus of the user's operation.
    • paused , when the activity loses focus but it remains visible to the user. That is, the other activity is on top of it and the activity is transparent or not covering the entire screen, so through it you can see the activity of the paused state. A paused activity is completely alive (it maintains all state and member information, and remains attached to the window manager), but can be killed by the system when the memory is very small.
    • Stop State When the activity is completely obscured by other activities. It still retains all state and member information, but it is not visible to the user, so its window is hidden and is often killed by the system when memory is needed elsewhere .

If an activity is paused or stopped, the system can remove it from memory by requiring it to end (by calling its finish () method), or simply by killing its process. When it is displayed to the user again, it must be fully restarted and restored to its previous state. As the activity transitions from one state to another, the change is notified by invoking the following protected method:

    • void OnCreate (Bundle saveinstancestate)
    • void OnStart ()
    • void Onrestart ()
    • void Onresume ()
    • void OnPause ()
    • void OnStop ()
    • void OnDestroy ()

All of these methods are hooks, and you can rewrite the appropriate work when the state changes. All activities must be implemented onCreate () to do some initialization settings when the object is instantiated for the first time. Many activities also implement OnPause () to commit data modifications or prepare to stop interacting with the user.

Merging them together, these seven methods define the entire life cycle of the activity. There are three nested loops that you can monitor through these seven methods:

  • oncreate () The begins until the call ondestroy () ends. An activity in oncreate () does all the initial settings for the "global" state, in ondestroy ( ) to release all reserved resources in the . For example, there is a thread running in the background that downloads data from the network, and it may create threads in oncreate () ondestroy () .
  • The visual life time of the activity , from calling OnStart () to the corresponding call to onStop () . During this time, the user can see the activity on the screen, although it may not be running in the foreground and interacting with the user. Between the two methods, you can keep the resources you need to display the activity. For example, you can register a broadcast receiver in OnStart () to monitor changes that affect your UI and log off in onStop () . OnStart () and onStop () can be called multiple times because the activity is toggled back and forth between visible and hidden.
  • The active foreground life time , from calling Onresume () to the corresponding call to OnPause (). During this time, frequently in reuse and pause state transitions--for example, when a device goes to sleep or a new activity is started, call onPause ()When an activity returns or a new intent is transmitted when Onresume ()is called. Therefore, the code for both methods should be fairly lightweight.

The following figure illustrates the possible paths of States between the three loops and states. The shaded ellipse represents the primary state of the activity, and the rectangle represents the callback method that you can perform when the activity transitions between states.

Figure 1, Activity life cycle (Source: Android SDK)

The following table describes each method in more detail and locates it throughout the life cycle of the activity.

Note the killable column of the table above, which indicates whether the system can kill the active host process when the method returns with no other code executing the activity. Three methods (onPause (),onStop (),OnDestroy ()) are marked as Yes. Because OnPause () is the only guarantee that will be called before the process is killed, you should use OnPause () to write any persisted storage data.

Methods that are labeled no protect the active host process from being killed when they call. The activity is therefore a kill state, such as OnPause () returned to the Onresume () call period. The activity is not to be killed until onPause () returns again. In fact, no activity marked as killable can be killed by the system, but this only happens in extremely difficult situations where no other resources are available.

2. Save Activity status

When the system, rather than the user, closes an activity to save memory, the user may want to return to the active state before it. In order to get the status before the activity is killed, you can perform the active onsaveinstancestate () method. Android calls this method before the activity is easy to be destroyed, that is, before calling OnPause () . The parameter of the method is a Bundle object, in which you can record the dynamic state of the activity with a name value pair. When the activity starts again, theBundle is passed to onCreate () and the method after calling OnCreate ( ),onrestoreinstancestate () , so you can recreate the captured state using one or two.

Because the onsaveinstancestate () method is not always called, you should only use onsaveinstancestate () to record the temporary state of the activity, not the persisted data. You should use OnPause () to store persistent data.

3. Coordination Activities

When an activity initiates another activity, they all experience life cycle transitions. A pause may be a stop, however another boot. Sometimes, you may need to coordinate these activities. The sequence of callbacks for the life cycle is clearly defined, especially when the two activities are in the same process:

    1. The currently active OnPause () method is called.
    2. Next, the onCreate (),OnStart (), andOnresume () methods of the start activity are called sequentially.
    3. Then, if the gain is no longer visible on the screen, its onStop () method is called.

fix : The first section -- Onrestart () in the second column (description) in the first to second row of the table in the activity life cycle should be onstart ().
More than 1000 clicks, incredibly no one found this error, see everyone at all did not seriously see or say there is no meditation on the garden of any blog post, heartache! Or the water is more popular.

Component life cycle (ii)

Introduction

Application components have a life cycle--the first time Android instantiates their response intent until the end of the instance is destroyed. During this time, they are sometimes active, sometimes inactive, and sometimes visible to the user for the activity, sometimes invisible. The component life cycle discusses the life cycle of activities, services, and broadcast receivers-including their possible state during the life cycle, methods for notifying state changes, and the possibility of the process of hosting the components of those States being terminated and instances being destroyed.

Previous Android Development Tour: Component life cycle (i) describes the life cycle of activities and their possible state, notification state change methods. This article describes the life cycle of service and broadcast receivers:

    • Service life cycle
    • Broadcast receiver life cycle
1. Service life cycle

A service can be used in two ways:

    • It can be started and allowed to run until someone stops it, or it stops itself. In this mode, by calling context.startservice () start the service and by calling stops the service. The service can also be called by calling service.stopself () or stops itself. You only need to call stopservice () stops the service, regardless of the startservice ( ) the number of times.
    • can programmatically manipulate services by using related interfaces. The client establishes a connection to the service object and uses the connection to dial in the service. The connection is established by calling context.bindservice () , by calling closes. Multiple clients can bind to the same service. If the service has not started, bindservice () can choose to start it.

These two patterns are not completely separate. You can bind to a service that starts with StartService () . For example, a background music service can start by calling StartService () by using the intent object that defines the music playback. Until later, the user may want to do some control on the player or get some information about the current song, an activity will call Bindservice () to establish a connection with the service. In this case, the StopService () is actually not stopped until the last binding is closed.

Like activity, a service also has a lifecycle method that you can perform to monitor its state changes. However, there are fewer life-cycle methods than activities, only three and they are publicly owned (public) rather than protected (protected) (Description: The active life cycle method is protected):

    • void OnCreate ()
    • void OnStart (Intent Intent)
    • void Ondestory ()

With these three methods, you can monitor the two nested loops of the service life cycle:

    • The entire life time of the service (entire lifetime), from calling OnCreate () to calling Ondestory ()accordingly. Like an activity, the service does some initial setup in onCreate () and frees all resources in. For example, a music playback service can create a thread in onCreate () and then stop the thread in ondestory () .
    • The active life time of the service (active lifetime), starting with the call to OnStart () . This method passes parameters to the intent object that is passed to StartService () . The music service will open intent, learn which music to play and start playing.
      There is no corresponding callback method because the service stops without the OnStop () method.

StartService () and ondestory () are called by all services, whether through Context.startservice () or through Context.bindservice () started. However,OnStart () is only called by a service that is started by StartService () .

If a service allows other bindings to it, there are some additional callback methods to implement it:

    • IBinder onbind (Intent Intent)
    • Boolean onunbind (Intent Intent)
    • void Onrebind (Intent Intent)

The arguments passed by the Onbind () callback are intent objects passed to Bindservice () , and the arguments passed by theOnunbind () callback pass to Unbindservice () the intent object. If the service allows binding,Onbind () returns the communication channel that the client interacts with the service. The Onunbind () method can require a call to Onrebind ()If a new client connects to the service.

Explains the callback method for the service. Although it separates services initiated by StartService () and services initiated by Bindservice () , remembering any service, regardless of how it was started, could allow the client to bind to it, so any service may receive Onbind () and Onunbind () calls.

2. Broadcast receiver life cycle

A broadcast receiver has a callback method:void OnReceive (Context curcontext, Intent broadcastmsg). When a broadcast message arrives at the receiver, Android calls its onreceive () method and passes it to the intent object that contains the message. The broadcast receiver is considered to be active only when it executes this method. When onreceive () returns, it is inactive.

The process of having an active broadcast receiver is protected and will not be killed. However, the system can kill only inactive components at any time when the process is needed by other processes that occupy the memory.

This poses a problem when the response of a broadcast message is time-consuming, so it should be done in a separate thread, away from the main thread that the other components of the user interface are running. If the onreceive () derived thread then returns, the entire process, including the new thread, is judged inactive (unless the other application component in the process is active), it will put it in a crisis of being killed. The way to solve this problem is to onreceive () start a service and do the work in a timely manner, so the system knows that there is active work in progress.

Component life cycle (iii)

The Android system tries to keep an application process as long as possible, but it eventually needs to remove the old process when memory is low. To decide which process to keep and which process to kill, Android puts each process into a level of importance based on the components it is running on and the state of those components. The least important process is first killed, then the second lowest, and so on. There are a total of 5 levels. The following list is listed in order of importance:

  1. The foreground process , which the user needs for the current job. A process is considered a foreground process if any of the following conditions are met:
    1. It is running an activity that is interacting with the user (the onresume () method of the Activity object has been called).
    2. It hosts a service that is bound to an activity that interacts with the user.
    3. It has a service object that executes its life cycle callbacks (onCreate (),OnStart (),OnDestroy ()).
    4. It has a Broadcastreceiver object that executes his onreceive () method.

      Only a handful of foreground processes exist in a given time period. They will be killed only as a last resort-if the memory is too low to continue running. In general, at that time, the device reached a memory??? Status, so some foreground processes are killed to keep the user interface responsive.
  2. Visual Process , he doesn't have any foreground components, but still can affect what users see on the screen. A process that satisfies any of the following conditions is considered to be visible:
    1. It hosts an activity that is not a foreground, but it is still visible to the user (its onPause () method has been called). For example, this may be sent in if a foreground activity is a dialog box and the activity before the run is still visible behind the face.
    2. It is hosted by a service that binds to a visual activity.

      A visual process is considered to be important and will not be killed unless the foreground process is kept running.
  3. The service process is a service that runs with a StartService () method, and the service does not fall into the 2 categories above. Although the service process is not directly related to any user visible, they usually do what the user cares about (such as playing MP3 in the background or downloading data from the network), so the system keeps them running unless there is not enough memory to keep them with all foreground processes and visual processes.
  4. A background process is a onStop () method that maintains an activity that is not currently visible to the user (the active object has been called). These processes do not directly affect the user experience and can be killed at any time to reclaim memory for a foreground, visual, and service process. There are generally a lot of background processes running, so they remain in an LRU (least recently used, which is the least recently used, if you learn the operating system, you will find it very familiar with the memory of the page replacement algorithm LRU. List to ensure that the most recently used active process is finally killed. If an activity executes its life cycle method correctly and captures its current state, killing it has no detrimental effect on the user's experience.
  5. An empty process , which is a process that does not maintain an active application component. The only reason to keep this process available is as a cache to increase the speed of the next boot component. System processes kill these processes to balance the entire system resource between the process cache and the potential kernel cache.

Android marks the process as the highest level it can be, that is, the most important of the components active in the process (choosing the most important one as the importance of the process). For example, there is a process that hosts a service and a visual activity, and the level of the process is set to the visual process level rather than the service process level (because the visual process level is higher than the service process level).

In addition, the ranking of a process rises because other processes depend on it. A process serves other processes, and its ranking is never lower than the process it serves. For example, one of the content provider services in process A is a client in process B, or a service in process A is bound to a component in process B, and process A is always considered more important than process B.

Because one running a service process is ranked higher than a process running background activity, an activity initiates a service to initialize a long-running operation instead of simply deriving a thread-especially if the operation is likely to drag down the activity. Examples of this are playing music in the background and uploading pictures taken by the camera to a website. Use the service to ensure that the operation has at least the priority of the service process, regardless of what happens to the activity.

"Go" Android Development Tour: Component life cycle

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.