When an app is closed, the activity receives the onPause() and onStop() callbacks in succession. If the player is playing, you must stop it before its activity goes away. The choice of which callback to use depends on what Android version you’re running.

In Android 6.0 (API level 23) and earlier there is no guarantee of when onStop() is called; it could get called 5 seconds after your activity disappears. Therefore, in Android versions earlier than 7.0, your app should stop playback in onPause(). In Android 7.0 and beyond, the system calls onStop() as soon as the activity becomes not visible, so this is not a problem.

To summarize:

In Android version 6.0 and earlier, stop the player in the onPause() callback.

In Android version 7.0 and later, stop the player in the onStop() callback.

When the activity receives the onDestroy() callback, it should release and clean up your player.

Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.