Resolve some of the things you need to know about service

Source: Internet
Author: User

What is Service

Service, common-names services. In the Android system, service and activity are like a mother, not only look like, but also have some similar behavior (life cycle). For the activity, we are certainly not unfamiliar with the development of Android applications have dealt with the most in the activity, so today we use activity to introduce service. Service, like activity, is one of the four components of Android and needs to be registered in the Androidmanifest manifest file. Service is not run as activity in the foreground, and is echoed in the background to run the services, if the activity as the download software user interface, and the service is the silently running in the background of the download thread, So the service scenario is that we don't need it to be in the foreground but need it to work in the background, such as downloading, playing music, IM software listening client messages, etc.

Service Start-up

There are two ways to start a service, not monotonous and luxurious. In the component we can start the service with StartService (), which is similar to the activity startup mode, and use StopService () to shut down the start-up services, but can also use a more unique binding boot mode Bindservice () To start the service, the corresponding Unbind method is naturally unbindservice (). Of course, the difference between the two start-up means that the service has a different life cycle call method, we first look at the service startup code, in detail as follows:

Define a service class:

1 public class MyService extends Service {2     //onbind is an abstract method that must be implemented 3     @Override 4 public     ibinder Onbind (Intent arg 0) {5         return new Mybinder (); 6     } 7     @Override 8 public     void OnCreate () {9         super.oncreate ();     }1 1     @Override12 public     void OnDestroy () {         Super.ondestroy ();     }15     @Override16     public void Onrebind (Intent Intent) {         super.onrebind (Intent),     }19 @Override20 public     void OnStart (Intent Intent, int startid) {Super.onstart         (Intent, Startid);     }23     @Override24     public boolean onunbind (Intent Intent) {         return super.onunbind (Intent);}27/**28      * Constructs a Mybinder class, which inherits from the binder, and the binder implements the IBinder interface      */30 public     class Mybinder extends binder{31         // Return a reference to a service instance         MyService getId () {             myservice.this;34         }35     }36}

Starting mode is StartService:

Start a serviceintent intent = new Intent (this, myservice.class); StartService (intent);//Stop Servicestopservice (intent);

The life cycle of the StartService () startup mode is:

Context.startservice (), OnCreate (), OnStart (), Service Run, Context.stop (), OnDestroy (), Ser Vice is closed.

Starting mode is Bindservice:

A connection class that implements the Serviceconnection interface needs to be constructed first

1 Private class Myserviceconnection implements serviceconnection{2 public myserviceconnection () {} 3 @Override 4 pub LIC void onserviceconnected (ComponentName arg0, IBinder binder) {5 MyService MyService = ((myservice.mybinder) binder) . GetService (); 6//Bind succeeds call 7} 8 @Override 9 public void onservicedisconnected (ComponentName arg0) {10//Call 11}12 when service crashes)

Then bind the start service

Bind a serviceintent intent = new Intent (this, myservice.class); Myserviceconnection conn = new Myserviceconnection () Bindservice (Intent, Conn, context.bind_auto_create);// Unbind Serviceunbindservice (conn);

When we execute Bindservice (), the system will call OnCreate () and Onbinde (), and after the execution of the Onbind (), the Serviceconnection () method in onserviceconnected will be called back. It also returns a class that implements the IBinder interface (which typically returns a subclass that inherits to Binder, since Binder implements the IBinder interface), and then we can get an instance of the service from IBinder by some means (referring to the code above). Once you get the quote, you get the control, and then you have to play with the service and it's not your own business ...

Bindservice () Startup mode life cycle:

Context.bindservice (), OnCreate (), Onbind (), Service Run, Context.unbindservice (), Onunbind ()-&G T Service OnDestroy () is closed

The above two life cycle very formal implementation process, but the philosophical view tells us, there is a common exception, so there are some wonderful life flow of the existence is also possible.

Scenario One: when we call StartService () in the component to start the service, but we do not call StopService () to destroy it, then we StartService () to start the service again, Instead of calling OnCreate (), this callback method only executes OnStart (). Why is it? Because in the Android system, each service is set to a singleton mode, no matter how many times startservice () is called to start the service, the system will always run only one service. OnCreate () is called when the service is created, so the service does not call OnCreate () when it is repeatedly started, because the services already exist in the system, so only OnStart () is called. In other words, when the service is started multiple times, onCreate () is called only once, and OnStart () can be called multiple times.

Scenario Two: when we need to go through a service that starts with StartService (), calling StopService () will meet our small requirements, and this time the procedure is generally expected to execute OnDestroy (). But if we do not sacrifice stopservice () The sword, but kill the caller (such as activity) directly, will it execute the OnDestroy () method? The answer is no, because since the service has been started, it has been left with the caller, regardless of whether the caller is not a half-dime relationship with him, unless the StopService () through the intention (intent) to the service recovery, Of course all this is built on the premise that the service is initiated by StartService.

Scenario Three: now that the binding service (Bindservice) is in the same way as StartService, if multiple restarts of service,oncreate () will still only invoke the first time the service was created. and for Onbind () will be called every time the service is repeated binding, ask here Onbind () The most important role is to transfer ibinder back to the binder, borrow it to establish a binding and service contact. If there is more than one binding, then executing Unbindservice () will only trigger onunbind () without triggering OnDestroy (), and only the last binding call Unbindservice () will trigger the service's OnDestroy () of the call. Another special place is that if you destroy the binder (for example, activity), the bound service will follow him (execute Onunbid->ondestroy).

Little Tips on Service

1, if you need a caller will still not be destroyed after the exit, but also need to get his reference, then there is such a small method. First StartService () Start the service, then Bindservice bind the service, you can get a reference to a service, and then in the Unbind Unbindservice, because the first startservice will only execute Onunbind (), Because there is no binding, even if the caller hangs up, the service will still run as before.

2, service Although said to be running in the background, but actually said it is still running in the main thread, here said to run in the main thread is its oncreate, OnStart, Onbind and other life cycle methods run in the main thread, if these methods such as downloading, reading large files and other time-consuming work, Causes the main thread to block, so we typically run the business we need in the service with another driver thread.

3, service start, bind and stop, unbind should be in the corresponding caller's corresponding life cycle, for example, need service throughout the activity, we can re-oncreate in the start, bind service, Stop or unbind the service in OnDestroy. If you only need to run the service at the user's foreground, you should do so in OnStart and OnStop. It is not recommended to start stopping the service in OnPause and Onresume, as this can result in unnecessary performance depletion, for example, when two activity requires this service at the same time, when the previous activity's OnPause just ended the service, The next activity starts the service immediately in Onresume, causing some nasty problems.

4, some people think why in the Bindservice do not put IBinder back to the caller, this is because the service is started asynchronously, when the call Bindservice is not able to obtain IBinder and return, So can only be in the back by calling Onbind when the IBinder thrown into the onserviceconnected parameters.

5, some people will encounter onserviceconnected () after Bindservice is not called, please check your onbind () function, if the return value of NULL is not triggered by the callback of Onserviceconnected (), So we want to make sure that Onbind returns a class that implements the IBinder interface.

6. We can return true in the Onunbind () method, so that if we bind the service again after we unbind the service, we will call Onrebind (), the less common callback method, instead of executing onbind ().

Resolve some of the things you need to know about service

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.