In the same way.
When Service starts with Intent (or through PendingIntent ), Android will start the service, if necessary, call onCreate() if this happens, and then the onStartCommand(intent, flags, startId) , passing Intent and startId .
Service must manage its own life cycle and call stopSelf() , when this is done, when the service is destroyed by Android, the onDestroy() method is onDestroy() .
The only way to start a service is to bind to it from Activity . This does not call onStartCommand() ; instead, it calls onBind() .
Android terminates the service if
- service call
stopSelf() and not bound to it Activity - the service is not tied to Activity, there are no other links and other commands for which
stopSelf() not been called - Low resources on the device (
START_STICKY flags and these flags are used here)
The stopSelf() method has a version of stopSelf(int) . A call without parameters means: I finished with everyone, stopped me; calling it with an integer value: I do if after that no other command was received; the integer is one of the startId that you get in the onStartCommand() method. If you have a queue of operations executed one after another, it is natural to call stopSelf(int) after each operation, otherwise your Service should know when to call stop.
Thus, usually a Service should โknowโ what it is doing and stop when it is finished, but you can start the Intent with a specific action (say "ACTION_STOP") for this Service and process this action stopSelf() If it was started, this will stop it (it is your responsibility to close any background thread / release any resource, possibly in onDestroy() ). If it has not been started, it will start and stop immediately.
It says that I invite you to think about what you are doing. You didnโt specify, but your request is a bit strange, I canโt think of a reason why the service should be scheduled to close.
Finally, consider JobScheduler look at JobScheduler for Lollipop and later. It is better to use a battery.
Daniele segato
source share