Know when the user exits the app or puts it on background

I have set Up a timer service in my app which uses setInterval. It works fine but the problem I have is that the timer still runs when the user gets a call or exits the app. I have different sounds playing when the timer reaches certain points. The app still plays those sounds in the background.
Is there a way to find out if the app is in the background or foreground?