StartService usage and service life cycle in Android

Source: Internet
Author: User

There are two main ways to use service in Android, by invoking the StartService method of the context or by invoking the Bindservice method of the context, this article only discusses the use of StartService, Does not involve any Bindservice method invocation scenarios.

When we call the StartService method of the context, we start the service, and the service started by the StartService method runs indefinitely. The service stops running and is destroyed only if the service's Stopself method is called internally by the StopService or service that calls the context externally.

To use the service, first we inherit from the service, and then rewrite the following method:
OnCreate, Onstartcommand, Onbind and OnDestroy.

These are all callback methods, which are called by the Android operating system at the right time, and it is important to note that these callback methods are called in the main thread.

onCreate: When the StartService method is executed, the service is created and the service's OnCreate callback method is executed if the service is not running, or if the service is already running. Then executing the StartService method does not perform the service's OnCreate method. That is, if the StartService method of the context is executed more than once, the OnCreate method of starting the Service,service method will only be called once when the service is first created, and will not be called again at a later time. We can do some service initialization related operations in the OnCreate method.

Onstartcommand: After executing the StartService method, it is possible to invoke the service's OnCreate method, after which the service's Onstartcommand callback method will be executed. That is, if the StartService method of the context is executed more than once, the service's Onstartcommand method will be called several times accordingly. The Onstartcommand method is important, and we do the actual work in this method based on the incoming intent parameter, such as creating a thread here to download data or play music.

onbind: The Onbind method in the service is an abstract method, so the service class itself is an abstract class, that is, the Onbind method must be rewritten, even if we do not use it. When using the service through StartService, when we override the Onbind method, we only need to return it to null. The Onbind method is used primarily when invoking a service to the Bindservice method.

OnDestroy: Service initiated by the StartService method runs indefinitely, only if the stopservice of the context is called or when the Stopself method is called inside the service. The service will stop and destroy, and the service callback function will be executed when it is destroyed.

In order to explore the life cycle of the service initiated by the StartService method to verify the description of each callback function method, we have written a test case as follows.
First create a service class Testservice, which inherits from service, with the following code:

 PackageCom.ispring.startservicedemo;ImportAndroid.app.Service;ImportAndroid.content.Intent;ImportAndroid.os.IBinder;ImportAndroid.util.Log; Public  class testservice extends Service {    @Override     Public void onCreate() {LOG.I ("Demolog","Testservice, OnCreate, Thread ID:"+ Thread.CurrentThread (). GetId ());Super. OnCreate (); }@Override     Public int Onstartcommand(Intent Intent,intFlagsintStartid) {LOG.I ("Demolog","Testservice, Onstartcommand, Startid:"+ Startid +", Thread ID:"+ Thread.CurrentThread (). GetId ());returnStart_sticky; }@Override     PublicIBinderOnbind(Intent Intent) {LOG.I ("Demolog","Testservice, Onbind, Thread ID:"+ Thread.CurrentThread (). GetId ());return NULL; }@Override     Public void OnDestroy() {LOG.I ("Demolog","Testservice, OnDestroy, Thread ID:"+ Thread.CurrentThread (). GetId ());Super. OnDestroy (); }}

We simply print out the corresponding information in the various callback methods of Testservice, and do not do many complicated processing operations.

We then invoke the corresponding code in the serivce,activity in the activity as follows:

 PackageCom.ispring.startservicedemo;Importandroid.app.Activity;ImportAndroid.content.Intent;ImportAndroid.os.Bundle;ImportAndroid.util.Log; Public  class mainactivity extends Activity {    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); LOG.I ("Demolog","Thread ID:"+ Thread.CurrentThread (). GetId ()); LOG.I ("Demolog","before Test StartService");//Continuous start serviceIntent intent1 =NewIntent ( This, Testservice.class);        StartService (INTENT1); Intent Intent2 =NewIntent ( This, Testservice.class);        StartService (Intent2); Intent Intent3 =NewIntent ( This, Testservice.class); StartService (INTENT3);//Stop serviceIntent intent4 =NewIntent ( This, Testservice.class); StopService (INTENT4);//Start service againIntent INTENT5 =NewIntent ( This, Testservice.class);        StartService (INTENT5); LOG.I ("Demolog","after test StartService"); }}

In activity, we first call the activity's StartService method three times in a row to start the service, and then call the activity's StopService method to stop the service. The service is then started by invoking the activity's StartService method.

The output of the running program is as follows:

We analyze the above output, first print out the main thread ID is 1, and then we find that all the following in the callback function to print out the ID of the execution thread is 1, which means that the various callback methods in the service are running in the main thread. Secondly, we can find that after we have called three successive startservice methods, only one OnCreate callback method is triggered, and three times Onstartcommand method is triggered. In the Onstartcommand we can read the intent object passed through the StartService method, and this three times the Startid are different, respectively, is three-way, each call StartService will automatically assign a Startid, Startid can be used to distinguish between different startservice calls, in general Startid are counted from 1, and Startid automatically increments after each call to StartService.

We then called the activity's StopService (INTENT4) method to stop the service, and through the output we found that the service performed the OnDestroy method, In general, we can perform some resource-freeing operations in the OnDestroy method. An instance of the service is destroyed after the OnDestroy is executed. Although we have called the StartService method three times before, we can stop the running service and destroy it whenever we call StopService.

Finally, when we started the service again through StartService (INTENT5), we found that the service's OnCreate method was executed again through the output, which means the service was re-created after the StopService was destroyed. The Onstartcommand callback method is called again, and the Startid is counted again starting at 1.

We use a graph to summarize the life cycle of a service that starts with StartService:

When Android is in low memory, it may destroy the service you are running and then re-create the service when it is fully in memory. The behavior of the service being forcibly destroyed by the Android system and re-rebuilt depends on the return value of the Onstartcommand method in the service. The return values we use frequently have three values, Start_not_sticky, Start_sticky, and Start_redeliver_intent, and these three values are static constants in the service.

start_not_sticky: If Start_not_sticky is returned, it means that the service is not recreated when the process running on the service is forcibly killed by the Android system. Of course, if the startservice is called after it has been killed for some time, the service will be instantiated. In what context is it appropriate to return this value? We can set the return value of the Onstartcommand to Start_not_ if the work performed by one of our service is interrupted several times, or if it needs to be killed in the case of an Android memory shortage and does not immediately recreate the behavior. STICKY. For example, a service needs to periodically get the latest data from the server: Let the timer start the service to get the latest data from the servers with a timer every n minutes specified. When executing the onstartcommand of the service, another n-minute timer is programmed within the method to start the service again and open a new thread to perform the network operation. It doesn't matter if the service is forcibly killed by the Android system during the process of getting the latest data from the server, and the service is not re-created, because another n-minute timer will restart the service and retrieve the data again.

start_sticky: If the start_sticky is returned, the Android system will still set the service to started state (that is, the running state) after the process that the service runs is forcibly killed by the android system , but the intent object passed in by the Onstartcommand method is no longer saved, and then the Android system tries to recreate the service again and executes the Onstartcommand callback method. However, the intent parameter of the Onstartcommand callback method is null, which means that the Onstartcommand method does not get intent information, although it executes. If your service can run at any time or end without problems, and you don't need to intent information, you can return Start_sticky in the Onstartcommand method, For example, a service that plays a background music function is appropriate to return this value.

start_redeliver_intent: If Start_redeliver_intent is returned, the process running by the service is forced to be killed by the Android system, similar to the case of returning Start_sticky , the Android system will re-create the service again and execute the Onstartcommand callback method, but the difference is that The Android system will again retain the service before being killed in the last pass of the Onstartcommand method intent again and pass it again into the Onstartcommand method of the re-created service. This allows us to read the intent parameter. As soon as you return start_redeliver_intent, the Onstartcommand heavy INTENT must not be null. If our service needs to rely on specific INTENT to run (need to read related data information from INTENT, etc.), and it is necessary to re-create the operation after forced destruction, then such a service is appropriate to return to start_redeliver_intent.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

StartService usage and service life cycle in Android

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.