As one of the four components of Android, the service also has a lot of important knowledge points. Let's start with the basics.
1.1 The creation of a service first creates a Servicetest class that inherits the service. We will rewrite OnCreate (), Onstartcommand () and Ondestory () three methods, which are the most commonly used methods in each service. Where the OnCreate method is called when the service is created, the Onstartcommand method is invoked every time the service is started, and the Ondestory method is called when the service is destroyed. Normally, if we want the service to execute an action as soon as it is started, we can write the logic in the Onstartcommand method. When the service is destroyed, we should also recycle those resources that are no longer used in the Ondestory () method. It is also important to note that each service needs to be registered in the Androidmanifest.xml file in order to take effect. This is the feature of Android four components, do not know everybody noticed not.
1.2 Start and stop of service
After defining the service, you should consider how to start and stop the service. The way to start and stop a service is certainly not unfamiliar. The main use of intent to achieve.
To start the service code:
Intent startintent=new Intent (this,servicetest.class);
StartService (startintent); To stop the service code:
Intent stopintent=new Intent (this,servicetest.class);
StopService (stopintent);
Although learning how to start a service and stop the service, but do not know whether you have doubts in mind? What is the difference between onCreate () and Onstartcommand ()?
In fact, the OnCreate method is called when the service is first created, and the Eronstartcommand () method is invoked every time the service is started, the first click starts, the service has not been created, so two methods will execute. After starting the service several times, you will find that only the methods in Onstartcommand () can be executed.
Introduction to Android Service Services (i)