I'm writing an app which has a long-running service.
I've written some state-saving code in the service's onDestroy
method.
My intention is that this should be invoked if the service ever gets killed by Android, due to memory pressure.
How can I simulate the service being killed by memory pressure?
I've tried adb shell am force-stop com.example.app
but the service's onDestroy
method was not invoked.
Is onDestroy
a sensible site for service-shutdown-state-saving?
If so, how can I make a service's onDestroy
be invoked by Android, for debugging/testing purposes?
You should not rely on onDestroy()
because it only gets called, when service is properly stopped (by calling stopService()
or stopSelf()
method).
If you want to save service state, you should either save it as you go (for instance a player service can store it when play/pause function is activated), or use a timer to save it periodically.
If you want to react to memory events, you should use ComponentCallbacks2
class, which will notify you, when Android needs more memory. If you free memory inside those callbacks, you will increase probability your service will stay in memory longer.
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With