1. Service Usage
- Define a class (for example, EchoService), Inherit Service (Android.app.Service)
- Register the service in Androidmanifest.xml, such as <service android:name= "EchoService" ></service>
- Declares a intent:intent serviceintent = new Intent (mainactivity,echoservice.class);
- Start Service:startservice (serviceintent);
- Close Service:stopservice (serviceintent);
2. Service life cycle
- Create Service:oncreate ()
- Onstartcommand ()
- OnStart ()
- Destroy Service:ondestroy ()
- After the service is created, only the first oncreate is called before it is destroyed. During the run of the service, the OnCreate method is not executed, but Onstartcommand (),OnStart () are executed at the time the StartService is run.
3. Binding Service
- Binding: Bindservice (serviceintent,this,context.bind_auto_create);
- Bind_auto_create: Indicates that the service is automatically created if the service you want to bind is not already open.
- Unbind: Unbindservice (this);
The parameter in the above method of this, refers to a class implementation of the Serviceconnection interface, here is the mainacitivty implementation. And the method of the replication interface public void onserviceconnected (componentname name, IBinder service) and public void onservicedisconnected (Com Ponentname name) Method 3. Chen Gong is bound to execute the EchoService Onbind method, which returns an instance of the binder subclass. 4. Through the onserviceconnected got it.Binder Instance object, because binder is the internal class of the service and can be called into various methods within the services, so the activity can also do a variety of operations.
remark:If the service is initiated through StartService, he will not be destroyed by the destruction of the activity, but services initiated through Bindservice will be destroyed. If the service is started through StartService, it is only destroyed by StopService. The StartService method is automatically executed by starting the service through Unbindservice (this will crash the program) through Bindservice. and cannot be stopped by StopService, you can use Unbindservice to stop
"Android Beginner" 12, Service