What is a service
A service is a component without a visual interface that can run for long periods of time and perform various operations in the background.
Creation of services
We only need to inherit the service class and implement the appropriate method to create the services
To start the service, you also have to register the service in the Androidmanifest
Sample code for the service class
Package Com.whathecode.servicedemo;import Android.app.service;import Android.content.intent;import Android.os.ibinder;import Android.widget.toast;public class Extendsionservice extends service{/** * This method is called when the service is first created */@Overridepublic void OnCreate () {super.oncreate (); Toast.maketext (Getbasecontext (), "service was created", Toast.length_short). Show (); /** * This method is called when the service is started by the StartService method */@Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) { Toast.maketext (Getbasecontext (), "service was started", Toast.length_short). Show (); return Super.onstartcommand (Intent, flags, Startid);} @Overridepublic ibinder onbind (Intent Intent) {return null;} @Overridepublic void OnDestroy () {Super.ondestroy ();}}
Start a service using StartService
Logic code for the main interface:
Package Com.whathecode.servicedemo;import Android.app.activity;import Android.content.intent;import Android.os.bundle;import Android.view.view;public class Mainactivity extends activity{intent service = null;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main);//Create Services service = new Intent (this, extendsionservice.class);} public void Start (view view) {//Start service StartService;} public void Stop (view view) {//Stop services StopService (service);}}
Registration Service:
<service android:name= "Com.whathecode.servicedemo.BackgroundService" ></service>
Operating effect:
Attention:
When we first clicked the Start Service button, the OnCreate method and the Onstartcommand method were executed sequentially,
But in the second click to start the Service button, the service is already running, the OnCreate method no longer executes the second time,
The Onstartcommand method is always executed when invoking StartService to start the service.
The OnDestroy method executes after the StopService method is called.
In addition to using the StartService method to start the service, we can also use bind to start the service.
The difference between the former and the latter is:
The life cycle of a service is not dependent on the initiator. The service is running in the background after it has been started until the call StopService is stopped.
Using bind to start a service, the life cycle of the service depends on the initiator. That is, the service is automatically destroyed after the initiator exits.
Start a service using BIND mode
The service is started primarily using the Bindservice method, and the Unbindservice method destroys the service.
The advantage of starting a service this way is that the service returns a IBinder object when bind is successful.
We can access the specific methods within the service by implementing this object within the service class.
So as to achieve and serve the purpose of communication.
Attention:
We cannot invoke the method in the same way that the service is instantiated directly.
Other than that:
If you do not unbind when exiting the service, the program throws an exception IllegalArgumentException exception.
Therefore, each time a call to Bindservice starts the service, the need to exit the service after completion requires the use of Unbindservice to unbind.
Example code:
Package Com.whathecode.servicedemo;import Android.app.activity;import Android.content.componentname;import Android.content.intent;import Android.content.serviceconnection;import Android.os.bundle;import Android.os.ibinder;import Android.view.view;public class Mainactivity extends activity{intent service = Null;I Receptionist rpst;/** * Bindservice and Unbindservice methods used parameters */private Serviceconnection conn = new Serviceconnection () {// This method is called when the service connection is terminated unexpectedly, @Overridepublic void onservicedisconnected (componentname name) {}//calls this method automatically when the service is connected. The second parameter is the object returned in the service class Onbind method @overridepublic void onserviceconnected (componentname name, IBinder service) {Rpst = ( ireceptionist) Service;rpst.callextendsionnumber ();}}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main);//Create Services service = new Intent (this, extendsionservice.class);} public void Start (view view) {//Start service StartService;} public void Stop (view view) {//Stop service StopService (serviCE);} public void bind (view view) {//Bind service Bindservice (service, Conn, bind_auto_create);} public void UnBind (view view) {//Unbind service Unbindservice (conn);}}
Inherit the Servicebinder object and implement a custom interface:
In this way, we can expose only the methods needed to achieve the protection of the Code.
ireceptionist Interface Code:
Package Com.whathecode.servicedemo;public interface Ireceptionist {public void callextendsionnumber ();
Extendsionservice Service Class Code:
Package Com.whathecode.servicedemo;import Android.app.service;import Android.content.intent;import Android.os.binder;import Android.os.ibinder;import Android.util.log;import Android.widget.toast;public class Extendsionservice extends service{private static final String TAG = "Extendsionservice";/** * This method is called when the service is first created */@Overri depublic void OnCreate () {super.oncreate (); Toast.maketext (Getbasecontext (), "service was created", Toast.length_short). Show (); /** * This method is called when the service is started by the StartService method */@Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) { Toast.maketext (Getbasecontext (), "service was started", Toast.length_short). Show (); return Super.onstartcommand (Intent, flags, Startid);} @Overridepublic ibinder onbind (Intent Intent) {return new Servicebinder (); @Overridepublic void OnDestroy () {Toast.maketext (Getbasecontext (), "service destroyed", Toast.length_short). Show (); LOG.D (TAG, "service destroyed"); Super.ondestroy ();} public void Putextendsion () {Toast.maketext (Getbasecontext (), "Transferring extension for you", Toast.length_short). Show (); /** * * Inherit binder and implement Ireceptionist interface * The purpose of inheriting the binder class is to return the object of this type in the Onbind method * * Implementation of Ireceptionist interface is required to expose the method */private class ServiceB Inder extends Binder implements Ireceptionist{public void Callextendsionnumber () {putextendsion ();} private void Othermethod () {}}}
Operating effect:
Notice that when we press the Back button, the activity is destroyed and the service initiated by it is destroyed.
This kind of service seems to play a small role, there is no way to quit the activity when the service does not quit?
The answer is: Android allows us to start a service before calling Bindservice to bind to the service,
In this way, we can both achieve and serve the purpose of communication, but also enable the service to run in the background for a long time.
See:
The following diagram provides a clearer understanding of how the above code works:
Android four components--using the service for background operations