Service of Android Services

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?

The usual, first, a little 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 respectively corresponding to local, as well as remote, also corresponding to different ways to start the 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.

Package Com.dongzi;import Android.app.service;import Android.content.intent;import android.media.MediaPlayer;    Import Android.os.binder;import Android.os.ibinder;import Android.util.log;public class LocalService extends Service {     private static final String TAG = "LocalService";        Private IBinder binder=new Localservice.localbinder ();    @Override public IBinder onbind (Intent Intent) {return binder;    } MediaPlayer Mediaplayer=null;             @Override public void OnCreate () {log.i (TAG, "onCreate");            Here you can start the Media Player//if (mediaplayer==null)//Mediaplayer=mediaplayer.create (this, URI);     Super.oncreate ();             } @Override public void OnStart (Intent Intent, int startid) {log.i (TAG, "OnStart");     Super.onstart (Intent, Startid); } @Override public int onstartcommand (Intent Intent, int flags, int startid) {log.i (TAG, "Onstartcomman         D "); Return START_sticky;             } @Override public void OnDestroy () {log.i (TAG, "OnDestroy");     Super.ondestroy ();            }//define content class inherit Binder public class Localbinder extends binder{//return Local Service LocalService GetService () {        return localservice.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:

Start service    private void Startcustomservice () {         Intent intent=new Intent (this,localservice.class);         StartService (intent);    }

  

The 2nd type of binding method:

LocalService Localservice=null;    Use the Bindservice method to start the service    private void Binderservice () {         Intent intent=new Intent (this,localservice.class);         Bindservice (Intent, New Serviceconnection () {            @Override public            void onserviceconnected (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 IBinder and returns the current local service                localservice= ((localservice.localbinder) binder). GetService ();                Here you can either prompt the user, or invoke some method of the service            }            @Override public            void onservicedisconnected (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.



Next, we will explain some of Aidl's knowledge. These are closely related to the service.

Service of Android Services

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.