Service is one of the four major Android components, no user interface, has been running in the background.
Why use a service to start a new thread to perform time-consuming tasks instead of initiating a sub-threading process directly in the activity?
1, activity will be exited by the user, the activity of the process becomes an empty process (no active component of the process), the system needs memory may be a priority to terminate the process;
2, if the host process is terminated, then all the child threads within the process will also be terminated, which may cause the child thread to be unable to perform the completion;
3, in fact, both methods are able to deal with time-consuming tasks, the use of different scenes.
First, start the service via start mode
This way the sevice is started, and there is no association between the visitor and the service, even if the visitor exits the service still executes
Life cycle: OnCreate ()->onstartcommand ()-OnDestroy ( )
Defines a subclass that inherits the service
Public classNormalserviceextendsService {@Override Publicibinder onbind (Intent arg0) {return NULL; } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {Toast.maketext ( This, "Start Successful", Toast.length_short). Show (); LOG.D ("Normalservice", "Start successful"); //This is where a new thread is typically started to perform time-consuming operations return Super. Onstartcommand (Intent, flags, Startid); }}
"In the Androidmanifest.xml file, configure the service
<android:name= "Com.android.servicetest.service.NormalService" />
"is used in activity.
Private void Startnormal () { new Intent (); Nomalintent.setclass (this, normalservice. class ); StartService (nomalintent);}
Second, start the service by bind mode
This way the Sercice is started, the visitor is bound together with the service, the visitor exits, and the service terminates.
Life cycle: OnCreate ()->onbind ()->onunbind ()->ondestroy ()
Defines a subclass that inherits the service
Public classBinderserviceextendsService {Private intcount; PrivateMybinder Mbinder; @Override Publicibinder onbind (Intent arg0) {if(Mbinder = =NULL) {Mbinder=NewMybinder (); } toast.maketext ( This, "Bind succeeded", Toast.length_short). Show (); LOG.D ("Binderservice", "Bind succeeded"); returnMbinder; } @Override Public voidonCreate () {Super. OnCreate (); NewThread (NewRunnable () {@Override Public voidrun () { while(true) { Try{Thread.Sleep (1000); Count++; } Catch(Exception e) {}}} }). Start (); } Public classMybinderextendsBinder { Public intGetCount () {returncount; } }}
"In the Androidmanifest.xml file, configure the service
<android:name= "Com.android.servicetest.service.BinderService"/>
"is used in activity.
PrivateMybinder Mbinder; PrivateServiceconnection conn =Newserviceconnection () {@Override Public voidonservicedisconnected (ComponentName arg0) {} @Override Public voidonserviceconnected (componentname arg0, IBinder binder) {Mbinder=(Binderservice.mybinder) binder; }};Private voidBindservice () {bindintent=NewIntent (); Bindintent.setclass ( This, Binderservice.class); Bindservice (Bindintent, Conn, service.bind_auto_create);}
@Override protected void OnDestroy () { super. OnDestroy (); Unbindservice (conn);}
The binder object corresponds to the internal hook of the service component, which is associated to the bound service component;
When other program components bind the service, the service returns the binder object to other program components, and other program components can communicate with the service component in real time through the binder object.
Iii. Intentservice, services for handling asynchronous requests
Intentservice is a subclass of service that adds additional functionality:
Using a queue to manage request intent, Intentservice joins the intent in the queue whenever the client code starts Intentservice through intent requests, and then opens a new worker thread to process the intent in the queue. Therefore, the main thread is not blocked.
Intentservice processes the intent in the queue in order, which guarantees that only one intent is processed at the same time.
The realization of "Intentservice"
Public classIntentservicetestextendsintentservice{ Publicintentservicetest () {Super("Intentservice"); } @Overrideprotected voidonhandleintent (Intent arg0) {Toast.maketext ( This, "Start Successful", Toast.length_short). Show (); LOG.D ("Intentservicetest", "Start successful"); //This method can perform time-consuming operations LongEndTime = System.currenttimemillis () + 20 * 1000; while(System.currenttimemillis () <endTime) { synchronized( This) { Try{Wait (endTime-System.currenttimemillis ()); }Catch(Exception e) {}}} }}
"In the Androidmanifest.xml file, configure the service
<android:name= "com.android.servicetest.service.IntentServiceTest"/>
"is used in activity.
Private void Startintentservice () { new Intent (); Serviceintent.setclass (this, intentservicetest. class ); StartService (serviceintent);}
Iv. Invoking Service (aidl service) across processes
Android applications are running in their own processes, the process is not directly exchanged between the data, in order to issue such cross-process communication, Android provides the Aidl Service.
"To create a Aidl file that defines the source code for the interface must end with. aidl
Package Com.android.servicetest.service; Interface imusic{ String getName (); String getYear ();}
Once the Aidl interface is defined, the ADT tool automaticallygenerates a Imusic interface in the gen/com/android/servicetest/service/directory;
The interface contains a stub inner class that implements the IBinder interface in addition to implementing the Imusic interface, which will act as a callback class for the remote service.
"Defines a service implementation class
Public classMusicserviceextendsservice{PrivateMusicbinder Mbinder; @Override Publicibinder onbind (Intent arg0) {if(Mbinder = =NULL) {Mbinder=NewMusicbinder (); } toast.maketext ( This, "Bind succeeded", Toast.length_short). Show (); LOG.D ("Musicservice", "Bind succeeded"); returnMbinder; } Public classMusicbinderextendsimusic.stub{@Override PublicString GetName ()throwsRemoteException {return"Compendium of Materia Medica"; } @Override PublicString GetYear ()throwsRemoteException {return"2006"; } }}
"In the Androidmanifest.xml file, configure the service
<android:name= "Com.android.servicetest.service.MusicService"/>
"is used in activity.
PrivateIMusic Musicservice;PrivateServiceconnection =Newserviceconnection () {@Override Public voidonservicedisconnected (ComponentName arg0) {} @Override Public voidonserviceconnected (componentname arg0, IBinder binder) {//gets the proxy for the object returned by the Onbind method of the remote serviceMusicservice =IMusic.Stub.asInterface (binder); }};Private voidBindaidlservice () {aidlintent=NewIntent (); Aidlintent.setclass ( This, Musicservice.class); Bindservice (Aidlintent, Connaidl, service.bind_auto_create);}Private voidshowcontent () {String content= ""; Try{content= Musicservice.getyear () +Musicservice.getname (); } Catch(Exception e) {} toast.maketext ( This, Content, Toast.length_short). Show ();}
@Override protected void OnDestroy () { super. OnDestroy (); Unbindservice (connaidl);}
This is a very small difference in how the service is tied up, except for the way the service callbacks are obtained:
The return value of the Onbind method can be obtained directly when the service is bound, and the agent of the object returned by the Onbind method is obtained when binding the remote service.
Android Services (service) research