Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill an android service?

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?

like image 836
fadedbee Avatar asked Sep 16 '15 20:09

fadedbee


1 Answers

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.

like image 79
sergej shafarenka Avatar answered Sep 20 '22 02:09

sergej shafarenka