I am looking for a place to put my clean up code (e.g. releasing file handles, shutting down services).
Here is the scenario: I have an app with multiple activities and a service running in the background. The service accesses a lot of sensors and files. Thus, it must be stopped if the app is terminated by the user to prevent battery draining. However, the service must continue running while the app is in the background and/or the screen is turned off. I am looking for a place to stop the service in code. onDestroy() of my Activities seems not to be a good idea because Android may call it (even while my app is running) or may call it never at all.
Is there a good place for releasing used resources of an app when the user knowingly terminates it?