Overview of StartService Basic use methods in Android _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 explores the use of pure startservice, Does not involve any Bindservice method calls. If you want to learn more about Bindservice, see the basics of how to use Bindservice in Android.

When we start the service by invoking the StartService method of the context, the service that is started through the StartService method runs indefinitely. The service stops running and destroys only if the Stopself method of the service is invoked outside the StopService or service inside the context.

To use a service, we first inherit from the service, and then rewrite the following methods:
onCreate, Onstartcommand, Onbind and OnDestroy.

These methods are all callback methods that are invoked by the Android operating system at the right time, and note that these callback methods are invoked 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, and if the service is already running, Then executing the StartService method does not perform the OnCreate method of the service. That is, if the StartService method of the context is executed multiple times, the OnCreate method to start the Service,service method is invoked only once when the service is first created, and will not be invoked again. We can do some service initialization related operations in the OnCreate method.

Onstartcommand: After the StartService method has been executed, it is possible to invoke the service's OnCreate method, after which the service's Onstartcommand callback method is bound to be executed. In other words, if the StartService method of the context is executed more than once, the Onstartcommand method of the service will be invoked multiple times accordingly. The Onstartcommand method is important, and we do it in this method based on the incoming intent parameters, such as creating a thread here to download data or play music.

Onbind: The Onbind method in 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 cannot use it. When we use the service through StartService, when we rewrite the Onbind method, we just need to return it to null. The Onbind method is used primarily to invoke the service for the Bindservice method.

OnDestroy: A service that starts with the StartService method runs indefinitely, only when the stopservice of the context is invoked or when the Stopself method is invoked 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 service launches through the StartService method to verify the descriptions of the various callback function methods above, a test case is written below.
First create a service class Testservice, which inherits from service, and the code is as follows:

 package Com.ispring.startservicedemo;
Import Android.app.Service;
Import android.content.Intent;
Import Android.os.IBinder;

Import Android.util.Log; public class Testservice extends Service {@Override public void onCreate () {log.i ("Demolog", "Testservice-> oncr
  Eate, Thread ID: "+ thread.currentthread (). GetId ());
 Super.oncreate (); @Override public int Onstartcommand (Intent Intent, int flags, int startid) {log.i ("Demolog", "Testservice-> on
  Startcommand, Startid: "+ Startid +", Thread ID: "+ thread.currentthread (). GetId ());
 return start_sticky; @Override public IBinder onbind (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.currentthr
  EAD (). GetId ());
 Super.ondestroy (); }
}

We simply print out the corresponding information in each callback method of Testservice, and do not do many complex processing operations.

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

 package Com.ispring.startservicedemo;
Import android.app.Activity;
Import android.content.Intent;
Import Android.os.Bundle;


Import Android.util.Log; public class Mainactivity extends activity {@Override protected void onCreate (Bundle savedinstancestate) {Super.onc
  Reate (savedinstancestate);

  Setcontentview (R.layout.activity_main);

  LOG.I ("Demolog", "Thread ID:" + thread.currentthread (). GetId ());

  LOG.I ("Demolog", "before Test StartService");
  Continuous start service Intent intent1 = new Intent (this, testservice.class);
  StartService (INTENT1);
  Intent Intent2 = new Intent (this, testservice.class);
  StartService (Intent2);
  Intent Intent3 = new Intent (this, testservice.class);

  StartService (INTENT3);
  Stop service Intent intent4 = new Intent (this, testservice.class);

  StopService (INTENT4);
  Start service again Intent intent5 = new Intent (this, testservice.class);

  StartService (INTENT5);
 LOG.I ("Demolog", "after Test StartService"); }
}

In our activity, we first called 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 StartService method of the activity.

The output of the running program is as follows:

We analyze the output above, first print out the main thread ID is 1, and then we found that all of the following in the callback function printed in the ID of the execution thread is 1, which means that each callback method in the service is run in the main thread. Second, we can find that after we have called the three-time StartService method in succession, only one OnCreate callback method is triggered, triggering three onstartcommand methods. In Onstartcommand we can read the intent object passed through the StartService method, and these three startid are different, respectively, 1,2,3, and each call StartService automatically assigns a startid, Startid can be used to distinguish between different startservice calls, in general Startid are counted from 1 onwards, after each call StartService Startid automatically add an increment.

We then called the activity's StopService (INTENT4) method to stop the service, and by the output we found that the service executed the OnDestroy method, In general, we can perform some resource-free operations in the OnDestroy method. An instance of the service is destroyed after the OnDestroy has been executed. Although we have called the StartService method three times before, we can make the running service stop and destroy as long as the stopservice is called once.

Finally, when we started the service again via StartService (INTENT5), we found that the OnCreate method of service was executed again, indicating that the service was recreated after the StopService was destroyed. It then calls the Onstartcommand callback method again, and Startid starts counting again from 1.

The last thing to note is that we write two output codes at the beginning and the end of the service in the activity, respectively

Copy Code code as follows:
LOG.I ("Demolog", "before Test StartService");

And

Copy Code code as follows:
LOG.I ("Demolog", "after Test StartService");

But let's look at the output and see that the program directly comes up after the output of before Test StartService, but immediately after the test StartService, after that is the Testservice internal callback method output, This means that the StartService () method and the StopService () method are returned immediately after execution, that is, neither of these methods is blocking, and the start service and stop service are asynchronous operations, StartService (), StopService () sends the intent object to the Android framework, and the framework layer asynchronously starts and stops the service.

Let's use a picture to summarize the lifecycle of a service launched through StartService:

When Android is running out of memory, you may be able to destroy your current service and then recreate the service when you have enough memory. The behavior of the service being forced to be destroyed by the Android system and rebuilt again depends on the return value of the Onstartcommand method in the service. Our commonly used return value has three values,Start_not_sticky, Start_sticky, and Start_redeliver_intent, all of which are static constants in the service.

Start_not_sticky: If you return to Start_not_sticky, it means that the service will not be recreated when the service runs a process that has been forcibly killed by the Android system. If, of course, the StartService is invoked some time after its being killed, the service will be instantiated again. In what context would it be appropriate to return that value? If the work performed by one of our service was interrupted several times, or if it was necessary to be killed in the case of an Android memory strain and would not be recreated immediately, then we could set the Onstartcommand return value to Start_not_ STICKY. For example, a service needs to get the latest data from the server on a regular basis: use a timer to start the service at the specified n-minute intervals to get the latest data from the servers. When the Onstartcommand to the service is executed, another n minute timer is planned 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 forced to kill the Android system in the process of getting the latest data from the server and the service will not be recreated, because the timer will start the service again and retrieve the data again in N minutes.

Start_sticky: If you return to Start_sticky, which means that the service running process is forced to kill by the Android system, the Android system will still set the service to started state (that is, running state) , but no longer saves the intent object that the Onstartcommand method passes in, and then the Android system tries to re-create the service again and executes the Onstartcommand callback method. However, the intent parameter of the Onstartcommand callback method is null, that is, the Onstartcommand method executes but does not get the intent information. If your service can run or end at any time without any problems, and you do not need intent information, then you can return Start_sticky in the Onstartcommand method, For example, a service that plays the background music function is suitable to return the value.

start_redeliver_intent: If you return to start_redeliver_intent, it means that the service running process has been forcibly killed by the Android system, similar to the return of Start_sticky , the Android system will re-create the service again and execute the Onstartcommand callback method, but the difference is, The Android system will once again save the service in the last pass in the Onstartcommand method before it is intent again and pass it back into the Onstartcommand method of the recreated service. So we can read the intent parameter. As long as return to Start_redeliver_intent, then Onstartcommand heavy INTENT must not be null. If our service needs to rely on a specific INTENT to run (need to read the relevant data from the INTENT), and after the forced destruction is necessary to re-create the run, then this service is suitable to return to start_redeliver_intent.

The above is about the basic use of startservice and its life cycle introduction, I hope to help you learn

Related Article

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.