How to kill an android service?

16,048

Solution 1

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.

Solution 2

If you want to programmatically stop your Service, within the Service, call stopSelf().

Alternatively go to the app settings and do a force stop.

Solution 3

A force stop will not call onDestroy on any components, neither service nor activity. It completely closes the app without any further considerations.

I'm not sure about this but if your service isn't running as foreground service you can close it by removing the app from recent apps menu.

Share:
16,048
fadedbee
Author by

fadedbee

Updated on June 04, 2022

Comments

  • fadedbee
    fadedbee almost 2 years

    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?

  • fadedbee
    fadedbee over 8 years
    Sorry, where are the "app settings" (Android 4.0.3)
  • akodiakson
    akodiakson over 8 years
    How would you uninstall an app? Usually there's a screen dedicated to that and has a "FORCE STOP" option.
  • fadedbee
    fadedbee over 8 years
    I use adb shell pm uninstall com.example.app, or google play, to uninstall an app. I've not yet seen screen where I can uninstall an app on the phone.
  • fadedbee
    fadedbee over 8 years
    Found it, thanks - a long press of the home button brought up a list of the activities.
  • fadedbee
    fadedbee over 8 years
    FORCE STOP did not cause onDestroy to fire :(
  • akodiakson
    akodiakson over 8 years
    Android will kill Services impolitely like @Commonsware says. Impolitely meaning onDestroy won't be invoked.