Detailed explanation of service in Android (I)
This paper analyzes the service in android in detail. Share with you for your reference, as follows:
1、 Service Introduction
Service is a solution to realize the background running of programs in Android. It is suitable for performing tasks that do not need to interact with users and require long-term running. Service is one of the four components in the Android system (activity, service, broadcastreceiver and ContentProvider). It is similar to the level of activity, but it cannot run by itself, can only run in the background, and can interact with other components.
Service does not run in an independent process, but depends on the application process in which the service is created. When an application process is killed, all services that depend on the process will also stop running.
2、 Service initial practice
Create an Android project testservice.
1. Create a new service
When creating a service, it inherits the service class and overrides the oncreate method, onstartcommand method and ondestroy method.
2. Modify androidmanifest.xml
After creating a new service, you need to register in androidmanifest.xml, as follows:
3. Layout file activity_ main.xml
4. Mainactivity.java file
3、 Test results
After the project is published, it is as follows:
After clicking the "start service" button, the following will pop up in sequence:
In addition, if you click the "start service" button many times, the upper right figure will pop up instead of the upper left figure. Because the oncreate method is called only when the service is created, but the onstartcommand method is called every time the service is started.
After clicking "stop service", the following is displayed:
Summary: the startup process of Android service is as follows:
Call the startservice method of context -- oncreate method -- onstartcommand method -- service running.
The stopping process of Android service is as follows:
Service running -- call stopservice method of context -- ondestroy method -- service stop.
For more information about Android components, readers who are interested can see the special topic of this site: summary of the usage of Android basic components
I hope this article will help you in Android programming.