My Android service is stopping abruptly and a new

2019-03-06 06:33发布

问题:

I have a very simple Android GPS logging app that runs a service. The Activity is nothing but a start/stop button to control the service. On a button click, I start a new background service (with START_STICKY). Then I close the Activity and the service runs normally. I can run the app again to stop the service.

The service simply logs GPS coordinates to file. I am Logging in every method and Exception catch. At some point, could be minutes or hours, my service will stop, but onDestroy is not called and no exceptions are thrown. The logs simply show my last file write worked and then nothing. I suspect GC is killing it, but I thought START_STICKY basically meant "please run me as long as possible". 30 seconds later, a new copy of the service is started (different PID), onCreate and onStartService are called as usual.

Will Android kill a service if/when it kills its parent Activity or Application? Is it necessary to run the service in a separate thread to prevent this? Why would the full service life-cycle not complete (onDestroy is not called)?

回答1:

A Service is actually running in the main thread, and if you do work that could take some time you should create a new thread. Android can do this for you if you use an IntentService instead of the regular Service.

I should add that Android will kill a process that occupie the main thread for more than 5(?)s. Locking the main thread will cause an ANR (Application Not Responding), and maybe this is what you experience in your Service.



回答2:

Android does not terminate a background service when its parent activity is closed. But it suspends background jobs when device screen is locked. Your problem may be related to this. When screen is unlocked again, the service is expected to continue its work from where it left.