Search code examples
androidandroid-serviceondestroy

Why onDestroy method of a Service Not Calling when mobile switch off?


My requirement is send a request to the server with mobile switch on/off status and update the mongodb database mobile switch on/off status. To do this I am using an Service. In my Service onCreate method I added the code to send a request with switch on status and update database. It is working properly. I need to send switch off status when mobile switched off and that code part I added to Service onDestroy method. But it is not working , at least Service onDestroy method is not calling when mobile switch off.

Can Anyone give me the solution for that and How to I send a request from Service when Mobile switched off ?


Solution

  • Android is not obligated to go through the entire application lifecycle when it is shutting down the system. Just like it does not call onDestroy if the application crashes.

    One way you can generally work around this is instead of relying on the application to explicitly report being alive/dead, you have it periodically report in. Then you consider the application dead if it does not report in for a certain period.