What is the difference between START_STICKY and START_NOT_STICKY while implementing services in android? Could anyone point out to some standard examples.. ?
The documentation for START_STICKY
and START_NOT_STICKY
is quite straightforward.
START_STICKY:
If this service's process is killed while it is started (after returning from
onStartCommand(Intent, int, int))
, then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to callonStartCommand(Intent, int, int)
after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback.
Example: Local Service Sample
START_NOT_STICKY:
If this service's process is killed while it is started (after returning from
onStartCommand(Intent, int, int))
, and there are no new start intents to deliver to it, then take the service out of the started state and don't recreate until a future explicit call toContext.startService(Intent)
. The service will not receive aonStartCommand(Intent, int, int)
call with anull
Intent because it will not be re-started if there are no pending Intents to deliver.This mode makes sense for things that want to do some work as a result of being started, but can be stopped when under memory pressure and will explicit start themselves again later to do more work. An example of such a service would be one that polls for data from a server: it could schedule an alarm to poll every
N
minutes by having the alarm start its service. When itsonStartCommand(Intent, int, int)
is called from the alarm, it schedules a new alarm for N minutes later, and spawns a thread to do its networking. If its process is killed while doing that check, the service will not be restarted until the alarm goes off.
Example: ServiceStartArguments.java