The life cycle of the service
After the service is started, the Onstartcommand () method is called back, and if the service is created for the first time, the OnCreate () method is invoked. After the service starts, it runs until the StopService () or Stopself () method is called. Although the StartService () method is called every time,
But there is only one instance of the service. So no matter how many times the StartService () method is called, the service will stop just by invoking the StopService () or Stopself () method.
Call the Bindservice () method of the context to get a connection to the service, call the service's Onbind () method, and return an instance of the IBinder object so that it can communicate with the service. As long as the connection to the service is not disconnected, the service remains in a running state.
So when the StartService () method is called and the StopService () method is called, the OnDestroy () method in the service executes, indicating that the service is destroyed. When the Bindservice () method is called and the Unbindservice () method is called, the OnDestroy () method is also executed. If an activity is called the StartService () and Bindservice () methods, then we will call the StopService () and the Unbindservice () method at the same time so that the Ondestory () method will be executed.
These traverse the life cycle of the service.
Service
Service to be registered in Androidmanifest.xml
Creation of the service:
Public classLongrunningserviceextendsService {@Override Publicibinder onbind (Intent Intent) {return NULL; } @Override Public voidonCreate () {Super. OnCreate (); } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) { return Super. Onstartcommand (Intent, flags, Startid); } @Override Public voidOnDestroy () {Super. OnDestroy (); }}
The Onbind () method is an abstract class, so it must be implemented. When the service is first called, OnCreate () is called and the Onstartcommand () method is called. The call to the service will not call the OnCreate () method immediately after calling the Onstartcommand () method. Ondestory () method
is called when the service is destroyed.
Basic usage of Android Learning Service