Detailed android--> Service

Source: Internet
Author: User

The Android service is something that runs in the background, with the same level of activity. Since the service is running in the background services, then it is not visible, there is no interface of things. You can start a service to play music, or log changes in the location of your geographic information, or start a service to run and listen to some kind of action all the time.

The service, like all other components, runs in the main thread, so it cannot be used to make time-consuming requests or actions. You can open one by one threads in a service and take time-consuming actions in the thread.

So how exactly does the service work?

In order to be a scarce classmate, let's start with some basic knowledge.

A Basic knowledge

Services are generally divided into two types:

1: Local Service for internal applications. The service can call Context.startservice () to start and call Context.stopservice () to end. Internally you can call Service.stopself () or Service.stopselfresult () to stop yourself. No matter how many times startservice () is called, only one StopService () is called to stop.

2: Remote service is used between applications within the Android system. Interfaces can be defined and exposed for other applications to operate. The client establishes a connection to the service object and invokes the service through that connection. Call the Context.bindservice () method to establish a connection and start to call Context.unbindservice () to close the connection. Multiple clients can bind to the same service. If the service is not loaded at this time, bindservice () loads it first.
Available for reuse by other applications, such as defining a weather forecast service, and providing calls to other applications.

So let's look at the service life cycle first:


Context.startservice ()->oncreate ()->onstart ()->service running --Call Context.stopservice ()->ondestroy ()

Context . Bindservice ()->oncreate ()->onbind ( ) ->service Running --Call >onunbind () OnDestroy () from the appeal can be known to correspond to local, as well as remote, and also correspond to different ways of initiating this service.

Two Actual combat

We can define a local service to inherit services, and then play the media player in this service or record the change in geographic location. Sometimes our service interacts with the activity, so we can define an inner class to return the service, and of course we have to consider that if the services are started in a binding manner, then the inner class can be defined as inheriting the binder and then returning to the local service with the following code.

View Code
 PackageCom.dongzi;ImportAndroid.app.Service;ImportAndroid.content.Intent;ImportAndroid.media.MediaPlayer;ImportAndroid.os.Binder;ImportAndroid.os.IBinder;ImportAndroid.util.Log; Public classLocalServiceextendsService {Private Static FinalString TAG = "LocalService";PrivateIBinder binder=NewLocalservice.localbinder (); @Override PublicIBinder Onbind (Intent Intent) {returnBinder } MediaPlayer mediaplayer=NULL; @Override Public voidOnCreate () {log.i (TAG, "onCreate");//You can start the media player here .//if (mediaplayer==null)//mediaplayer=mediaplayer.create (this, URI);            Super. OnCreate (); } @Override Public voidOnStart (Intent Intent,intStartid) {log.i (TAG, "OnStart");Super. OnStart (Intent, Startid); } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {log.i (TAG, "Onstartcommand");returnStart_sticky; } @Override Public voidOnDestroy () {log.i (TAG, "OnDestroy");Super. OnDestroy (); }//define content class inheritance Binder     Public classLocalbinderextendsbinder{//back to Local serviceLocalService GetService () {returnLocalService. This; }    }        }

We can tell from above

Define content class Inheritance Binder
public class Localbinder extends binder{
Back to Local Service
LocalService GetService () {
return localservice.this;
}
}

You can return to this service, and the activity can invoke the service's method through the service.

So how do you start the service? From the above basic knowledge, we know there are 2 ways, as follows:

View Code
  // Start the service     privatevoid startcustomservice () {         Intent intent=new Intent (this , LocalService. class);         StartService (intent);    }

The 2nd type of binding method:

View Code
LocalService localservice=NULL;//start the service with the Bindservice method    Private voidBinderservice () {Intent intent=NewIntent ( This, LocalService.class); Bindservice (Intent,NewServiceconnection () {@Override Public voidOnserviceconnected (componentname componentname, IBinder binder) {//call the Bindservice method to start the service, if the service needs to interact with the activity,//The Onbind method returns the IBinder and returns the current local serviceLocalservice= ((Localservice.localbinder) binder). GetService ();//Here you can either prompt the user, or invoke some method of the service} @Override Public voidonservicedisconnected (ComponentName componentname) {localservice=NULL;//Here you can prompt the user}}, Context.bind_auto_create); }

When binding the service, need a service connection object, Serviceconnection, once the service is connected, it will call the Onserviceconnected method, we can return our local service object in this method, see the code While the Onservicedisconnected method is called when the service is disconnected, we can clean up some of the service resources.


Note: The service cannot be started by itself, only by invoking the StartService and Bindservice methods from the Context object. That is, the service cannot be called by itself, so we see that many service calls are made with activity.

(1) Context.startservice (): Service will experience OnCreate, OnStart (If the service is not already running, Android calls OnCreate () and then calls OnStart (), or only onstart () if the service is running. So a service's OnStart method may be called repeatedly); StopService Direct OnDestroy,if the caller exits directly without calling StopService, the service will run in the background. The service can be shut down by StopService after the caller has started up again. Note that multiple calls to Context.startservice () are not nested (even if the corresponding OnStart () method is called), so no matter how many times the same service is started, once the Context.stopservice () or stopself is called ( ), he will be stopped. Supplemental Note: The intent object passed to StartService () is passed to the OnStart () method.The call order is: onCreate---OnStart (can be called multiple times)--OnDestroy.
(2) Context.bindservice (): Service will go through OnCreate (), Onbind (), Onbind will return to the client a Ibind interface instance, ibind allow the client to callback the service method, such as getting the service running state or other operations. This time the caller (Context, for example, activity) is bound to the service,context exits, Srevice will call Onunbind---ondestroyed corresponding exit, so-called binding together on the survival of a common
Supplemental Note: The intent object passed to Bindservice () is passed to Onbind (), and the intent object passed to Unbindservice () is passed to the Onunbind () method. The call order is: onCreate---Onbind (one time, not multiple bindings)--Onunbind----ondestory.
(3) Note: In the service every time the turn off process, only onstart can be called multiple times (through multiple StartService calls), other Oncreate,onbind,onunbind, Ondestory can only be called once in a life cycle. Also, I have not encountered the need for StartService and bindservice interaction (I think there is no such requirement), so there is no need to consider the problem of interaction, the treatment is not too late to consider.
(4)Broadcastreceiver can only start service via StartService, because the broadcast itself has a short life cycle, and bind doesn't make sense.

Playservice.java is the service class,

Includes three methods of Oncreate,onstart,ondestroy,

Where OnCreate is optional, if there is, you can create a link with mediaplayerd here. If none, you can create this link inside the onstart.

OnCreate is created only once in the music playback cycle (not OnDestroy), and OnStart is called once per-press play.

OnStart, the inside can start playing music,

OnDestroy, inside call to stop playing music.

If you press the Stop button, the (or print log is more intuitive) "Servicondestroy" is called, but the activity does not exit.

When exiting the activity, will be called (or print log more intuitive) "Activityonstop", and "Activityondestroy" at this time, music playback will not stop,

It can be known that if you want the service to start the execution of code, can be written in the service OnCreate or OnStart, which will be automatically invoked when the service is started, and the activity automatically call OnCreate the same reason.

Detailed android--> 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.