Android development: Service

Service is one of the four major components of Android. It runs in the background and is invisible

Service is not a separate process. The Service object itself does not mean that it runs in its own process. Unless otherwise specified, it runs in the same process as the program. .

Service is not a thread, but runs in the main thread. If you want to perform some time-consuming operations of downloading data, you need to open a sub-thread, otherwise it will cause an ANR exception.

Service has two startup modes:

1. startService: life cycle-onCreate-onStartCommand-onDestory; the running process is that when startService is called for the first time, the service life cycle will execute the onCreate and onStartCammand methods, but the second call will execute onStartCammand. When stopService is called, the onDestory method will be executed during the life cycle of the Service.

There are two ways to stop the Service: the context calls stopService or the Service itself calls stopSelf.

The type of return value in the onStartCommand method:

      START_STICKY sticky service constant 1 when the service is killed by the system exception, the service will be restarted but the Intent value is null  
      START_NOT_STICKY non-sticky service constant 2 when the service is killed by the system exception the service will not restart
      START_REDELIVER_INTENT constant 3 when the service is killed by the system exception After that, the service will restart and the Intent has the value
      START_STICKY_COMPATIBILITY constant 0 When the service is abnormally killed by the system, the service will not necessarily restart. The compatible version of START_STICKY understands

2. BindService: Lifecycle-onCreate-onBind-onUnbind-onDestory The methods of the Service lifecycle are only called once during the running process.

1. When multiple clients have a binding relationship with a Service, the life cycle of the Service will only be executed once, but
 the onServiceConnected method in the class that monitors the status change of the service link in the Client will be executed (when connecting for the first time) )

2. When multiple clients have a
  binding relationship with a Service , only when all Cilents have called the unBindService method, the Service will execute onUnbind

3. When the service has been unbound, you cannot contact the binding again, you need to make a mark to mark that the service is currently unbound

      BindService: Allow the Client to link with the Service and get the Service object and interact with it

      In order to provide this binding function, the onBind() method must be implemented, and the service object needs to be returned through the IBinder mechanism.


Guess you like

Origin blog.csdn.net/u010256329/article/details/51693677