2013年9月2日 星期一

START_STICKY, START_NOT_STICKY, START_REDELIVER_INTENT

All these are to tell android system what to do if the service is got 'killed'

As you know, there are lots of services keep running in the background and they will consume some memory. For simplicity, under 2 situation will the services being terminated:
- When our device memory goes down to a critical level it will automatically start terminating services to release memory.
- Users manually stopped the services (Oh! I find you the invisible memory killer!! Go to die!!! .\ /. )

Sometimes services that doing important tasks could also get terminated. You might want to relaunch these services later when the device memory gets stable (OMG unkillable service appear!!). So here we have 3 actions to choose:
- START_STICKY: tells the system to create a fresh copy of the service, when sufficient memory is available, after it recovers from low memory. here you will loose the results that might have computed before.
- START_NOT_STICKY: tells the system not to bother to restart the service, even when it has sufficient memory.
- START_REDELIVER_INTENT: tells the system to restart the service after the crash and also redeliver the intents that were present at the time of crash.

Usually this action will be defined in the function onStartCommand of a service:
@Override
public int onStartCommand(Intent intent, int flags, int startId){
 //TODO do something useful   
 Log.d(TAG,"onStartCommand");
 // Do something here, for example pop a notification
 return Service.START_NOT_STICKY; 
}

沒有留言:

張貼留言