This article blog introduces another very important component of Android, Service. Service and activity are similar, except that it runs in the background, is invisible, and has no interface. Service priority is higher than activity, when the system load is too large, will kill Activty, but the service is difficult to be purged by the system. It is important to note that the service also runs in the main thread and does not take a direct time-consuming operation, but instead needs to open a new thread in the service and take the time-consuming action on that thread. Service is mainly divided into local services and remote services. Let's start by learning local services.
How services are started
There are two main ways to start a service: Start mode and bind mode, we first look at the characteristics of these two ways
Start Mode:
1. The service does not have any connection with the startup source
2. Unable to get service object
Bind mode:
1. Through the IBinder interface instance, return a Serviceconnection object to the startup source
2. The service object can be obtained by means of the Serviceconnection object
In this blog post, we'll start with the starting mode service.
Start Mode startup service
Similar to initiating activity, the service is also started and stopped by intent, with the following code:
Switch (View.getid ()) { case r.id.start_bt: startintent=new Intent (mainactivity. this, StartService. class ); StartService (startintent); Break ; Case R.ID.STOP_BT: stopservice (startintent); Break ; }
Start, the custom StartService class inherits from the service class:
Public classStartServiceextendsservice{@Override Public voidonCreate () {Toast.maketext (), Getapplicationcontext (),"Start_service", Toast.length_short). Show (); Super. OnCreate (); } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {Toast.maketext (Getapplicationcontext (),"Startcommand_service", Toast.length_short). Show (); return Super. Onstartcommand (Intent, flags, Startid); } @Override Public voidOnDestroy () {Toast.maketext (), Getapplicationcontext (),"Stop_service", Toast.length_short). Show (); Super. OnDestroy (); } @Nullable @Override Publicibinder onbind (Intent Intent) {return NULL; }}
It is important to note that the OnCreate method is only called when the service is first created, and multiple startservice only call the Onstartcommand method before the service is stopped.
Finally, don't forget to register your service in the manifest file:
<service android:name= ". StartService "></service>
Android Learning--service (i)