Difference between service life cycle and activity life cycle

Source: Internet
Author: User
Tags call back

The life cycle of a component

The application component has a lifecycle from the Android instance that responds to intent to the instance being destroyed. During this period, they may be effective or ineffective, and may not be visible to users when they are in effect. Here we discuss the life cycle of four basic components, including the various states during the life cycle, and transitions between states. The possible result of these States is that the process makes them stop, and then the instance is destroyed.
First, Activity life cycle
An activity has three basic states:
@ When activity is running in the foreground (at the top of the stack of activity's current task), it is active or running. The activity responds to the user's actions.
@ Paused paused when activity loses focus but is still visible to the user. At this point, other activity is on top of him, transparent or fully covered. So some of these paused activity can also be displayed. A paused activity is active (he maintains all of the state's information and remains attached to the window manager).
@ If an activity is completely obscured by another activity, he will be in the stop state. But it still retains its original state and information. However, if more memory is needed elsewhere and the activity remains hidden, the system may kill his process.
If an activity is paused or stopped, the system can clean up the memory they occupy, or call the finish () method, or simply end his process. When he is shown to the user again, it will completely rerun and load the previously stored information.
The transition between activity states is done through the previous protected method:
void OnCreate (Bundle savedinstancestate)
void OnStart ()
void Onrestart ()
void Onresume ()
void OnPause ()
void OnStop ()
void OnDestroy ()

These are hook functions, you can rewrite them and do some proper processing when the state changes. All activity must implement the OnCreate () method to initialize the installation during the first run. Activity can implement OnPause () to commit data changes, and then prepare to stop interacting with the user.
Calling a Super Class

Each implemented activity lifecycle method invokes the parent class's method first, for example:
View Plaincopy to Clipboardprint?
protected void OnPause () {
Super.onpause ();
. . .
}
protected void OnPause () {
Super.onpause ();
. . .
}

By comparing the two, these 7 methods define the entire life cycle of an activity. You can implement and monitor these three nested loops:

@ Entire life cycle
Calling the OnCreate () method and OnDestroy () is called an activity's complete life cycle. The activity performs all initialization installations in OnCreate () and frees all remaining resources in the OnDestroy () method. For example, a thread that downloads a program from a network needs to be created in the OnCreate () method and destroyed in the OnDestroy () method.

@ Visible life cycle
The visible life cycle is the time from the OnStart () method to the OnStop () method. During this time, the user will see the activity on the screen. Although he may not be displayed at the top level, there is no interaction with the user. Between these two methods, you can keep the resources that you need to display to the user. For example: You can register a broadcastreceiver in the OnStart () method to detect certain changes to change your interface, and you can unregister the Broadcastreceiver in OnStop () when the user does not see the activity interface. These two methods can be called many times, when visible and hidden to the user, as the standby activity is on standby.

@ Front Display Period
An activity from the Onresume () method directs a OnPause () method called the foreground display cycle. At this point he displays and interacts with the user on top of other activity. An activity can frequently be excessive between these two methods, for example: when the device sleeps or another new activity starts, it enters the OnPause () state, and when an activity is completed or a new intent request is received, The activity's Onresume () is called. Therefore, the amount of code in both methods is very small.

Explains the above-mentioned loops, which indicate whether the two States can be converted from one to the other. Colored ellipses are the main states of activity. Squares and rectangles represent some of the callback methods that we can implement when the activity transitions between states.

Note The Killable column, which indicates whether the process can be killed by the system after the call method returns, without executing other code. OnPause (), OnStop (), and OnDestroy () these three methods can, because the OnPause method is executed first, he is the only one that is bound to be called when the process is killed, but the onStop () and the OnDestroy () method do not. Therefore, you can save some contiguous data in the OnPause () method, such as editing.
Killable This column is labeled as no, protecting the activity from being killed by the process when they are called. For example: An activity is in a state that can be killed, and when the activity jumps from the OnPause () method to the Onresume () method, it will not be killed until the OnPause method callback.

As in the following chapters: Processes and lifecycles, an activity that is not defined as "killable" can still be ended by the system, but this can happen in special cases, such as when there are no other resources.

Save status of activity

When the system (not the user) shuts down an activity to save memory, the user wants to start the activity again and return to that state.
In order to capture his state before the activity is killed, you can implement the Onsaveinstancestate () method, which is called by Android when an activity is about to be closed, that is, before the OnPause () method. He passed back to the method a Bandle object, you can save your data in a key-value way. When the activity is running again. This Bandle object is passed to the OnCreate () method, the OnStart () method, the Onrestoreinstancestate () method. These methods can reconstruct the activity state at that time.

Unlike OnPause () and several other methods just discussed, the Onsaveinstancestate () and Onrestoreinstancestate () methods are not life cycle methods. is not always called. For example, Android calls the Onsaveinstancestate () method before the activity is destroyed by the system, and does not call this method when the activity instance is destroyed by the user's actions (for example, by pressing the back key). There is no reason to save his state in this case.

Coordinating activities
When an activity initiates another activity, they all experience the transition of the life cycle. One paused or ended, and the other activity started. One situation you may need to adjust these activity:
The callback sequence of the life cycle method is defined, especially if two activity is under the same process:

1. The OnPause () method of the currently running activity is called.
2. The OnCreate (), OnStart (), and Onresume () methods of the activity that will be run are then called sequentially.
3. Then, if the activity to be run is not too visible, then the OnStop () method is called.
Second, the service life cycle:
With the Service class, how do we start him? There are two ways to do this:

Context.startservice ()
Context.bindservice ()
1. Invoking the StartService () method anywhere in the same application can start the service, and the system will callback the service class's OnCreate () and the OnStart () method. This starts the Service running in the background until the Context.stopservice () or Selfstop () method is called. In addition, if a Service has been started, the other code attempts to call the StartService () method, is not executed onCreate (), but will be re-executed once OnStart ().
2. Another bindservice () method means that the service is tied to the client class that invokes the service, and if the call to this client class is destroyed, the service is destroyed. One advantage of this method is that after the Bindservice () method executes the service will callback the above mentioned Onbind (), you can return from here a class that implements the Ibind interface, the class will be able to communicate with the client, such as getting service The State or other action of the run. If the service is not running, using this method to start the service will onCreate the () method without calling OnStart ().
Summarize:
1. The purpose of StartService () is to callback the OnStart () method, which is called when the service does not exist, if the service exists (for example, a bindservice was previously called), and the OnCreate () method Then the OnCreate method of the service has been called) then StartService () will skip the OnCreate () method.
2. Bindservice () is intended to call back the Onbind () method, which is used to establish a bridge between the service and the caller, and is not responsible for more work (for example, a service needs to connect to the server), Bindservice is typically used to bind to an existing service (that is, services initiated through StartService).
Because the OnStart () method of the service is called only when the service is started by StartService (), it is important to note this when using OnStart ().
Communicate with the Service and let it run continuously
What if we want to keep communication with the service and don't want the service to exit with the Activity? You can first StartService () and then Bindservice (). The Unbindservice () method executes when you do not need to bind, and executing this method only triggers the service's onunbind () and does not destroy the service. This allows the communication to be maintained with the Service and will not be destroyed as the Activity is destroyed.
Increase Service Priority
The Android system has its own method for memory management, in order to guarantee the orderly and stable operation of the system, the internal system will automatically allocate and control the memory usage of the program. When the system feels that the current resources are very limited, in order to ensure that some high-priority programs can run, it will kill some of the programs or services that he considers unimportant to free memory. This will ensure that programs that are really useful to the user are still running again. If your Service is in this situation, you will probably be killed first. But if you increase the priority of the service to let him stay a little more, we can use Setforeground (true) to set the service priority.
Why the foreground? The service that is started by default is marked as background, and the activity that is currently running is generally marked as foreground, which means that you set the service to foreground so that he has the same priority as the running activity. A certain increase. When this doesn't guarantee that your Service will never be killed, it just increases his priority.
Third, the life cycle of Android service is similar to activity, but there are some differences:
OnCreate and OnStart are different.
We can start a service by calling the Context.startservice (Intent) method from the client. If the service is not yet running, Android will start it and call its OnStart method after the OnCreate method. If the service is already running, then its OnStart method will be called again by the new intent. So it is completely possible and normal for a single running service to have its OnStart method repeatedly invoked.

Onresume, OnPause, and onstop are not needed.

Callback a service usually does not have a user interface, so we do not need onpause, Onresume or OnStop methods. Whenever a running service it is always running in the background.
Onbind
If a client needs a persistent connection to a service, then he can call the Context.bindservice method. If the service does not run the method will create the service by calling the OnCreate method but does not call the OnStart method to start it. Instead, the Onbind method is called by the client's intent, and it returns a Ibind object so that the client can invoke the service later. It is normal for the same service to be started and bound by the client at the same time.
OnDestroy

As with activity, a OnDestroy method will be called when a service is terminated. Android will end this service when no client is started or bound to a service. As with many activity situations, Android may also end a service when memory is low. If this happens, Android may also try to start the terminated service when memory is sufficient, so your service must persist the information for restart, and it is best to do so within the OnStart method.

--------------------------------------------------------------------------------------------------

Life cycle of activity

OnCreate (Bundle savedinstancestate): Called when the activity is first created. Here is where you do all the initialization settings-creating views, binding data to lists, and so on. If there was a status record, calling this method will pass in a package object that contains the previous state of the activity as a parameter

Onrestart (): Called after activity is stopped and before it is started again.

OnStart (): Called when the activity is about to become visible to the user.

Onresume (): Called before activity begins to interact with the user. The activity is at the top of the stack and accepts user input.

OnPause (): Called when the system will start another activity. This method is mainly used to persist unsaved changes and stop the CPU-like actions such as animations. This should be done in a short period of time, because the next activity must wait until this method returns before continuing.

OnStop (): This method is called when activity is no longer visible to the user. This can happen if it is destroyed or another activity (possibly existing or new) returns to the running state and overwrites it.

OnDestroy (): Called before activity is destroyed. This is the last call the activity receives. This can happen at the end of the activity (calling its finish () method) or temporarily destroying an instance of this acitivity because the system requires space. You can use the Isfinishing () method to differentiate between these two situations.

Coordinate activity

When one activity launches another, they all experience life cycle changes. One pauses or stops, while the other starts. In this case, you may need to coordinate these activity:

The life cycle callback sequence is defined, especially if two activity is within the same process:

1. Call the OnPause () method of the current activity.

2. Next, the OnCreate (), OnStart (), and Onresume () methods of the newly launched activity are called sequentially.

3. Then, if the activated activity is no longer visible on the screen, call its OnStop () method.

In summary: 1, activity from creation to enter the operating state of the event triggered by OnCreate ()-->onstart-->onresume ()

2. Event triggered from run state to stop State onPause ()--->onstop ()

3, from the stop state to the operating state triggered event Onrestart ()-->onstart ()--->onresume ()

4, from the operating state to the suspended state triggered event OnPause ()

5, from the suspended state to the operating state triggered event Onresume ()

Screen switching life cycle

1. When the activity's android:configchanges is not set, the screen will recall each life cycle, and will be executed once when the screen is cut and two times when the vertical screen is cut.

2. When you set the activity's android:configchanges= "orientation", the screen will recall the life cycle, and it will only be executed once when the screen is cut horizontally or vertically.

3. When you set the activity's android:configchanges= "Orientation|keyboardhidden", the screen does not recall the individual lifecycles, only the Onconfigurationchanged method is executed.

Life cycle of Service

When the service is started, the StartService and Bindservice () methods can be called to start, and the life cycle of the service started with these two methods is different.

The service life cycle is only Oncreate,onstart and OnDestroy, without Onresume,onpause and OnStop, most of the time the service is running, but it can also be killed by the system under severe memory pressure. If killed, the system will later attempt to restart the service

Invocation of Service

Pathway One:
Call Context.startservice () to start the service, call Context.stopservice () or service.stopself () or Service.stopselfresult () Closes the call to the service.

Service life cycle Analysis:
Note: Oncreate,onstart (), OnDestroy () is a service life cycle related method
When Context.startservice () starts the service, if the service itself is not running, call OnCreate ()->onstart () to complete service startup. If the service is already running, only OnStart () is called, and OnStart () can be called multiple times.
Service shutdown must call the Context.stopservice () or service.stopself () or Service.stopselfresult () method, close before calling the OnDestroy () method, Otherwise, if the context exits without stopping the service, the service will always run in the background. The caller of the service can only be restarted after the service is shut down via StopService.
Life cycle Order is: OnCreate ()->onstart ()->ondestroy ()

Pathway Two:
Call Context.bindservice () to initialize the binding, use Context.unbindservice () to unbind, because the service and context are binding, when the context exits or is destroyed, The service will also exit accordingly.

Service life cycle Analysis:
When Context.bindservice () is called, the service undergoes oncreate->onbind (), Onbind returns a Ibind instance to the client and ibind the method that allows the client to callback the service. At this point the context and service are bound together, the context exits, and service calls Onunbind ()->ondestroy () exits accordingly.
Life cycle Order is: Oncreate->onbind (only once, not multiple bindings)->onunbind->ondestroy ()

Broadcastreceiver can only start the service through StartService, because the broadcast itself has a short life cycle, and bind is meaningless.

If the service is not created through Bindservice (but still gets the service object through Bindservice), it may still be running after unbindservice, or it should end.

Difference between service life cycle and activity 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.