Android Four Components--service

Source: Internet
Author: User

Service RELATED LINKS

    • Service Initial involvement
    • Service Advanced
    • Service Proficiency

A service is a component of an Android system that is similar to the level of activity, but that it cannot run on its own, only in the background, and can interact with other components. A service is a long life-cycle code without an interface. A service is a program that can run for a long time, but it does not have a user interface. This is a bit boring, to look at an example, open a music player program, this time if you want to surf the internet, then, we open the Android browser, this time although we have entered the browser program, but the song play does not stop, but in the background to continue to play the next song. In fact, this play is controlled by the service that plays the music.
Of course, this music service can also be stopped, for example, when the playlist inside the song is finished, or the user pressed the Stop music play shortcut keys and so on. Service can be used in many applications, such as multimedia playback when the user initiates other activity, this time the program to continue to play in the background, such as the detection of changes in the file on the SD card, or in the background to record the changes in the location of the user's geographic information and so on. In short, the service is always hidden behind.

First, service life cycle and two start-up methods

The service life cycle is much simpler than the activity because the service is running in the background, it is running all the time, so there is no need for so much state judgment.  After it inherits only OnCreate (), OnStart (), or Onstartcommand (), //2.0 API level, implementing OnStart is equivalent to overriding Onstartcommand and returning About Onstartcommon (): http://blog.csdn.net/lizzy115/article/details/7001731

Three methods of OnDestroy ().

Life cycle diagram for service

Life cycle Analysis

Well, from the life cycle, we can know that there are two ways to use the service in Android:

1)StartService () Start service
2)Bindservice () Start service
PS: There is another, that is, after the service is started, bind service!

1) The relevant method is detailed:
  • onCreate (): When the service is first created and immediately callback the method, the method will only be called in sequence throughout the life cycle!
  • ondestory (): The method will be called back when the service is closed, and the method will only be recalled once!
  • Onstartcommand (Intent,flag,startid): The earlier version is OnStart (Intent,startid), which callbacks when the client calls the StartService (intent) method. The StartService method can be called multiple times, but no new service object will be created, but will continue to reuse the previously generated service object, but continue to callback the Onstartcommand () Method!
  • IBinder Ononbind (Intent): This method is a method that the service must implement, and the method returns a IBinder object that the app communicates with the service component through that object!
  • Onunbind (Intent): callback When all clients bound by the service are disconnected
2) Two kinds of starting mode

The service cannot run itself and needs to start the service by calling the Context.startservice () or Context.bindservice () method. Both of these methods can start the service, but they are used in different situations.

    1. The service is enabled with the StartService () method, the caller is not connected to the service, and the service is still running even if the caller exits. If you plan to start the service with the Context.startservice () method, the system calls the service's OnCreate () method first, and then calls the OnStart () method when the service is not created. If the StartService () method is called before the service has been created, calling the StartService () method multiple times does not cause the service to be created more than once, but results in multiple calls to the OnStart () method. Services started with the StartService () method can only call the Context.stopservice () method to end the service, and the OnDestroy () method is called at the end of the service.
    2. Using the Bindservice () method to enable the service, the caller and the service are bound together, and once the caller exits, the service terminates, and there is a "no need to live at the same time Must Die" feature. Onbind () The method is only invoked when the service is started with the Context.bindservice () method. This method is called when the caller and the service are bound, and the Context.bindservice () method is called multiple times when the caller is tied to the service and does not cause the method to be called more than once. Using the Context.bindservice () method to start a service can only call the Onunbind () method to disassociate the caller from the service and call the OnDestroy () method at the end of the service.
Second, registered service

The registration of the service is similar to the activity registration and is also registered in the Androidmanifest.xml file.

<android:name= ". MyService ">        <intent-filter>                 <   android:name= "Android.guo.service.playmusic.MyService"/>             </intent-filter>        </service>

To create a class that inherits from the Service

 Public class extends Service {    @Override    public  ibinder onbind (Intent Intent) {        //  TODO auto-generated Method Stub        returnnull;}

At present MyService can be considered empty, but there is a onbind () method is particularly eye-catching. This method is the only abstract method in the service, so it must be implemented in subclasses. We'll use the Onbind () method in a later section, which we can now temporarily ignore.

Since the definition of a service, nature should be in the service to deal with some things, the logic to deal with things should be written where? You can then rewrite some of the other methods in the service as follows:

 Public classMyServiceextendsService {@Override Publicibinder onbind (Intent Intent) {//TODO auto-generated Method Stub      return NULL; }
@Override Public voidonCreate () {//TODO auto-generated Method Stub      Super. OnCreate ();
LOG.V ("Mainactivity", "OnCreate")}
@Override Public voidOnStart (Intent Intent,intStartid) {//TODO auto-generated Method Stub      Super. OnStart (Intent, Startid); LOG.V ("Mainactivity", "OnStart"); }
@Override Public voidOnDestroy () {//TODO auto-generated Method Stub      Super. OnDestroy (); LOG.V ("Mainactivity", "OnDestroy"); } }

As you can see, here we rewrite the three methods of OnCreate (), Onstartcommand () and OnDestroy (), which are the three most commonly used methods in each service. where the OnCreate () method is called when the service is created, the Onstartcommand () method is invoked every time the service is started, and the OnDestroy () method is called when the service is destroyed.

Normally, if we want the service to execute an action as soon as it is started, we can write the logic in the Onstartcommand () method. And when the service is destroyed, we should reclaim those resources that are no longer used in the OnDestroy () method.

Also need to note that each service needs to be registered in the Androidmanifest.xml file in order to take effect, do not know if you have found that this is the four components of Android common features. So we should also modify the Androidmanifest.xml file, as shown in the code below:

< Service                Android:name = "Cn.com.qiang.service.MyService" >  </ Service >  

In this case, a service has been fully defined.

third, start and stop a service

We added two buttons to the layout file, which were used to start the service and stop the service. Then modify the code in the mainactivity as follows:

Button button1 =(Button) Findviewbyid (R.id.button1); Button1.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method StubIntent startintent =NewIntent (mainactivity. This, MyService.class);      StartService (startintent);            }  }); Button Button2=(Button) Findviewbyid (R.id.button2); Button2.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method StubIntent stopintent =NewIntent (mainactivity. This, MyService.class);      StopService (stopintent);  }  }); 

How can we verify that the service has been successfully started or stopped? The simplest way to do this is to add a print log to several methods of MyService, and you can see that we have joined in the MyService.

Let's look at the effect of the operation:

When the service is turned on, print in Logcat

After you close the service, print in LogCat:

Android Four Components--service

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.