In my application I have a foreground service running. I am able to stop the foreground service without issues when the user logs out. However, if the user swipes to close the app or the app crashes, I'm not able to handle stopping the foreground.

OnSleep() is called when the application closes/crashes, however it's also called when the app is backgrounded. The foreground service I am using MUST continue to run if the app has been backgrounded but I need to stop the foreground service when it has been closed as opposed to backgrounded, for this reason I cannot stop the foreground service in the OnSleep() method.

Is there any way I can know when the application is closing (Not being backgrounded) so I can handle stopping the foreground service?