Android Notes 01: Some knowledge about Service

1. What is Service?

A Service is an application component that runs in the background and performs time-consuming operations without a user interface. Other application components can start the Service, and when the user switches to another application scenario, the Service will continue to run in the background. In addition, a component can be bound to a service to interact with (IPC mechanism). For example, a service may handle network operations, play music, perform file I/O, or interact with content providers, all of these activities It's all done in the background.

2. Two states of Service

Service has two states started (started) and bound (bound).

1. Started services

Through the client, usually an Activity, a service can be started by calling startService, which we call StartedService, or UnboundService.

After the service is started through startService, it will run independently and has nothing to do with the client's Activity. The existence of the Activity does not affect the operation of the service. The service will stop only when the client calls stopService() or itself calls stopSelf(), and then the system destroys it

2. Binding services

The client can be bound to a Service by calling bindService from the client, but it should be noted that a ServiceConnection instance needs to be passed in the bindService method to monitor the success or failure of service binding.

After binding the activity to the service through bindService, the client (activity) can communicate with the service through an IBinder interface. When the activity ends, you need to manually call unbindService to unbind it from the service. A service can be bound to multiple clients. When all clients are unbound, the system will destroy the service.

 3. A service can be both unbound and bound

These two methods are not completely independent. After a service is started by startService, it can also be bound by the client. At this time, if stopService or stopSelf is called, the system will not destroy the service unless all clients are unbound from this service.

3. The declaration cycle of Serviced

 

  • Started service: Receive and process the intent passed by startService from onStartCommand(), and call stopService on the client or stopSelf on the service itself to end
  • Binding service: Receive and process the intent passed by bindService from onBind(), and end when the client calls unbindService

In short, a service that is both started and bound will only be destroyed by the system when all clients bound to it are unbound and stopService or stopSelf is called.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325064426&siteId=291194637