Android Stop Background Music

前端 未结 9 975
生来不讨喜
生来不讨喜 2020-12-01 02:29

EDIT - FOUND A EASY 5-10 LINE SOLUTION!!! See MY OWN ANSWER BELOW!!! YAY!!!!!!!!!

I\'ve searched for 5 hours, dozens of SO posts, no answers, and this seems like t

9条回答
  •  无人及你
    2020-12-01 02:36

    The way the media player works is that its runs as a service and then is stopped MANUALLY when the user stops it in the application itself.

    Example:

    When the media player is playing a song and the user hits home, obviously the user still wants to listen to the song as its a background task. After the user is done listening then the user manually stops it by going into the application and stopping (Aka stopping the service that is playing the song) it or if the playlist is done, then stop. Simple.

    This is the expected behavior. And it is exactly how the Music App works.

    UPDATE

    @Override
        protected void onPause() {
            super.onPause();
            if (this.isFinishing()){
                player.stop();
            }
        }
    

    Needs to be changed to

    @Override
        protected void onPause() {
            super.onPause();
            if (mediaPlayer != null){
                mediaPlayser.stop();
                if (isFinishing()){
                mediaPlayer.stop();
                mediaPlayer.release();
                }
            }
        }
    

    An explanation:

    The reason we are checking for the object not being null is obvious. However; when we enter the pause, we want to ensure that the mediaplayer is stopping. BUT if we are leaving and the song is almost done, then stop it and release it.

    UPDATE 2

    Check the link here:

    https://stackoverflow.com/a/6704844/529691

    This can be used to detect if your application has been moved out of the current tip of the application stack.

提交回复
热议问题