A service of the Startup type is a service started by another component by calling the startservice () method to generate a service that calls the onstartcommand () method of the service.
When a service is started, it has a life cycle independent of the components that start it, and the service can run in the background indefinitely even if its components are destroyed. Therefore, this service should terminate itself by calling the stopself () method at the end of work, or another component can terminate the service by calling the stopservice () method.
Application components such as activity can start the service by calling the startservice () method, and pass an intent object to the specified service, which also contains the data used by some services. The Service accepts this intent object in the onstartcommand () method.
For example, assume that an activity needs to save some data to the online database. This activity can start a service and pass the data to be saved to the startservice () method through an intent object. This Service accepts this intent object in the onstartcommand () method, connects to the Internet, and executes database transactions. When the transaction ends, the service is terminated and destroyed by itself.
Warning:The service runs in the same process as the application that declares it, and is in the main thread of the application. By default, if your service requires intensive or blocking operations and the user needs to interact with an activity of the same application, the service will reduce the activity performance. To avoid affecting the application performance, you should start a new thread inside the service.
Generally, you can inherit two classes to create started services:
Service
This is the base class of all services. When you inherit this class, it is important that you create a new thread for all service work, because the Service uses the main thread of your application, by default, the performance of a running activity may be reduced.
Intentservice
This is a subclass of a service class. It uses a working thread to process all startup requests in sequence. If you do not want the service to process multiple requests at the same time, this is the best choice. All you need to do is implement the onhandleintent () method, which accepts the intent object of each startup request to complete background work.