How to stop background music when application is not visible to the user

Solution 1:

The onPause() method that you can override in your activity will be called when the application is removed from the user's view.

Place whatever code you need to stop the music within that method, and you can be sure it will be called when the user presses 'back' or 'home'.

See here for the activity lifecycle:

http://developer.android.com/reference/android/app/Activity.html

Solution 2:

You can use the onPause()-Method of the Activity-Class to stop the background-music. When the app gets resumed you have start it again with onResume().

See: http://developer.android.com/reference/android/app/Activity.html#onPause%28%29