How to kill an android service?
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.
fadedbee
Updated on June 04, 2022Comments
-
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'sonDestroy
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 over 8 yearsSorry, where are the "app settings" (Android 4.0.3)
-
akodiakson over 8 yearsHow would you uninstall an app? Usually there's a screen dedicated to that and has a "FORCE STOP" option.
-
fadedbee over 8 yearsI 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 over 8 yearsFound it, thanks - a long press of the home button brought up a list of the activities.
-
fadedbee over 8 yearsFORCE STOP did not cause onDestroy to fire :(
-
akodiakson over 8 yearsAndroid will kill Services impolitely like @Commonsware says. Impolitely meaning onDestroy won't be invoked.