is it normal that the service is being destroyed when the app is put to the background(pressed the home button)? if it is, can i override it by commenting the onDestroy() function so that the service is not destroyed? i.e is it a good practice to do that.
-
show your code. Service will not be destroyed in such scenario – Suhail Mehta Feb 23 '15 at 09:01
-
Start service as foreground http://stackoverflow.com/questions/24839655/how-to-use-startforeground/24839801#24839801 – Ravi Shanker Yadav Feb 23 '15 at 09:04
-
its a huge code, so this is not a default command that is executed when the app goes to background? – Rashad.Z Feb 23 '15 at 09:05
1 Answers
Commenting out the onDestroy()
method will have no effect on this behavior; the Service
class abides by its lifecycle as described here.
To keep a Service
running in the background, the most common approach is to use a persistent notification. This is by design; Android doesn't want Services running in the background with no indication to the user that they're performing some activity and potentially draining battery and using system resources.
This is done by calling startForeground()
from the Service, and passing in a notification that will be shown to the user. More on this here.
In addition to this, another approach is to change the return value from onStartCommand()
in your Service to 'suggest' to Android that your Service should not be killed, or restarted if it is killed; however, this is not a guarantee that your Service will be kept running in low-memory situations. More on this here.
It's also good to ask: what is it that you're doing that requires a Service to run continually in the background? Often there are more efficient ways to accomplish such tasks.

- 1,576
- 4
- 15
- 23
-
thank you for your response, im a calling in a service that downloaded data from the web, and the user should be notified when new data arrives... same as a messaging app – Rashad.Z Feb 23 '15 at 09:11
-
Have you looked at using a service like Google Cloud Messaging (https://developer.android.com/google/gcm/index.html)? This is a great way to allow an app to be notified when new data arrives without keeping a resource-intensive service constantly running. Highly recommend looking at an approach like this. – dcarr622 Feb 23 '15 at 09:15