Tuesday, October 15, 2013

Special cases When the Services running in the background can be destroy?


 Services should carry out long running operations indefinitely, they are fated to be killed by the Android android system, if they are running in the back-ground.  

This is how it happens: 

 1) When a Service starts, it runs in the main process: A service when created does not create a separate thread/process for itself (unless instructed to do so); instead, it runs in the main thread of the running application, thus consuming the memory resources of the main system. 

 2) What happens in case of low system memory? The system would choose to close the components that are low priority, but are still consuming the system resources. Thus, the background components not in user focus are the first ones the system kills. Therefore, it would destroy the services running in the background. This is to free system resources for more important components (Example: for the activity in the foreground interacting with the user).

  3) Does system follow a pattern while killing services to free resources? Yes it does! Read on to find out:  a) Unbound Service: Over time, the system pushes down a long-running service to lower priority in the list of background tasks, and this service is more likely to close first (if unbound), when memory shortage occurs.  b) Services bound to foreground activity: The services that are bound to an activity or any other application component running in the foreground are less likely to be killed than an unbound activity.  c) Foreground Services: The system would never kill a service if it were declared to run in the foreground. We would discuss more about this in later Android tutorials. Stay put!  

4) How to keep a Service from being killed? a) You can create separate threads while creating services for the services to run. Thus, there is reduced consumption of main application memory, and the likelihood of the service being destroyed due to memory shortage is lower than otherwise.  b) As discussed before, you can declare a Service to run in the foreground. This can prevent the system from killing the Service

No comments:

Post a Comment