Service, as one of the four components of Android, must be the focus. Let's take a look at the lifecycle of the service, two ways to open it, and how to use it today.
There are two ways to open a service, a normal open, a binding way to open, of course, these two ways can be composed of hybrid open.
First, the normal opening of the serviceThe normal way to open a service is very simple, let's first look at how to define a service1. Write a class that inherits the service class.We don't care about the binder class in the code first. The follow-up explanation is used.
public class Testservice extends Service {@Overridepublic ibinder onbind (Intent arg0) {System.out.println ("Onbind"); return new Mybinder ();} @Overridepublic void OnCreate () {System.out.println ("create"); Super.oncreate ();} @Overridepublic void OnDestroy () {System.out.println ("OnDestroy"); Super.ondestroy ();} @Override @deprecatedpublic void OnStart (Intent Intent, int startid) {System.out.println ("start"); Super.onstart ( Intent, Startid);} @Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {System.out.println ("Onstartcommand"); return Super.onstartcommand (Intent, flags, Startid);} @Overridepublic boolean onunbind (Intent Intent) {System.out.println ("Onunbind"); return Super.onunbind (Intent);} Class Mybinder extends Binder implements IService {public void method () {System.out.println ("Servicemethod");}}
2, register service in manifest file
<service android:name= "Com.example.servicedemo.TestService" > </service>
3. Normal Open service
Intent = new Intent (Getbasecontext (), testservice.class); StartService (intent);
4. Normal Shutdown service
StopService (Intent);
What we should note here is that the intended object of the General Service will be made into global variables to facilitate the destruction of services at exit. This is the step for normal use of the service. During normal use, the life cycle of the service is this:Open: Oncreate-->onstartcommand-->onstartEnd: OndestoryNormally, the service is only opened once, only once the OnCreate method is executed, if the service is turned on, the StartService method is executed again, the Onstartcommand method and the subsequent method are skipped OnCreate. Where the OnStart method has been discarded
Second, the binding of the service opensSometimes we need to invoke the method in the service, and at this point we need to take a binding approach and start the service. On the principle of binding open service, this involves the binder mechanism of Android, which we are explaining in the next topic. Skip right here.To start the service in a binding way, we need to prepare a few things.1. Implement a class that inherits binder2, the activity inside realizes a realization Serviceconnection interface class.
1, the implementation of binder classBinds the service, calls the Onbind method, and then returns a IBinder proxy. So we need to implement a class that inherits binder. Then write a method in it and you can invoke the method in the service. Where IService is an interface class that allows for subsequent operations to remotely invoke the service method so that it is written together.
Class Mybinder extends Binder implements IService {public void method () {System.out.println ("Servicemethod");}}
Return this binder in the Onbind method.
@Overridepublic ibinder onbind (Intent arg0) {System.out.println ("Onbind"); return new Mybinder ();}
2. Get Agent BinderBecause binder implements the IService interface, we also get a class that implements the IService.
Class Mycon implements Serviceconnection {@Overridepublic void onserviceconnected (componentname arg0, IBinder binder) { IService = (iservice) binder;} @Overridepublic void onservicedisconnected (ComponentName arg0) {}}
3. Binding of service and calling service method
Intent = new Intent (Getbasecontext (), testservice.class); conn = new Mycon (); Bindservice (Intent, Conn, bind_auto_create) ;
When such a service is bound, the life cycle of the service is performed like this: Oncreate-->onbind, does not execute the Onstartcommand method, after getting the proxy class, we can execute the method in the service.
Findviewbyid (r.id.test). Setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {// StartService (intent); Iservice.method ();});
In this way, the method in the service is invoked. There is a risk of using a binding approach to the service, which means that if you start the service with a binding method, you will get an error when you minimize the program. The program will remind you to unbind the service in order to do so. This time we need to unbind the service in some actvity life cycle.
Unbindservice (conn);
Execute this line of code, you can unbind the service. The life cycle of the executed letter is: Onunbind-->ondestory
Third, the mixed opening of servicesBefore, we said that the use of binding to open the service, it will lead to minimize the time of the program error, then what solution? At this point, we need to start the service with a hybrid approach.The so-called hybrid open, is the service after the normal open service, in the binding method of binding. Let's see the code.
Intent = new Intent (Getbasecontext (), testservice.class); StartService (intent); conn = new Mycon (); Bindservice (Intent, conn, bind_auto_create);
This achieves the effect of mixed-turn-on services. The function of the life cycle that he performs is: Oncreate-->onstartcommand-->onstart-->onbind so when we exit, we need to unbind, stop the service
Unbindservice (conn); StopService (intent); conn=null;intent=null;
The life cycle functions performed at this time are: onunbind-->ondestory
Iv. methods for invoking remote servicesSometimes, we need to invoke the method of service in other applications, this is actually the implementation of the principle of the IPC mechanism of Android. Let's talk about the method code for implementing the steps today.1. Rename the interface file to a. aidl file
Package Com.example.servicedemo;interface IService {void method ();}
After we change the suffix name of the previous IService interface file to. aidl, we need to remove the modifier fields such as public inside.2. In the new application, create a new package with the same name as the previously stored. aidl file package.When you are new, copy the. aidl file into the package
3. How to implement binder in service class before modification
Class Mybinder extends Iservice.stub {public void method () {System.out.println ("Servicedemomethod");}}
After modifying the previous interface file, we directly inherit the interface file automatically generated. Stub class can
4. Define the open mode of the implicit trial intention of the service, and open the service with the implicit intentionBecause you can't get the class name of a service in another application, we need to use implicit intent to open the service and bind it.
<service android:name= "Com.example.servicedemo.TestService" > <intent-filter> <action Android:name= "Com.example.servicedemo.TestService.action"/> </intent-filter> </service>
Before binding the service, you need to rewrite the Proxy interface implementation class, where the cast is no longer used.
Class Mycon implements Serviceconnection {@Overridepublic void onserviceconnected (componentname arg0, IBinder binder) { IService = IService.Stub.asInterface (binder);} @Overridepublic void onservicedisconnected (ComponentName arg0) {}}
And then bind the service, you can invoke the remote service's method.
<span style= "White-space:pre" ></span>intent Intent = new Intent (); Intent.setaction (" Com.example.servicedemo.TestService.action "); Bindservice (Intent, New Mycon (), bind_auto_create); Findviewbyid ( r.id.test). Setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {try {iservice.method ();} catch (RemoteException e) {e.printstacktrace ();}}});
In the service use of the process, it should be noted that the end of the service, it is important to remember to release all the resources in the service, especially the service has to open the sub-thread and wireless loop.
Well, the basic use of services to the end of this explanation, I hope this article can help everyone.
An explanation of the service services for Android development