How do you detect if a user exits an app and if the app is in the background?

see: