简体   繁体   中英

OnDestroy() Being called for Service when app goes to background

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? ie is it a good practice to do that.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM