iamarnold
iamarnold

Reputation: 725

Android: Mediaplayer plays multiple times if I keep on pressing the back button and launch the app again

When I play my song and press the back button to return to return to home, the music continues playing. When I launch the app again, the music plays twice. I think it's the onResume method because I commented out the method and the problem stopped. How do I get onResume work properly? I tried using if(backgroundMusic.isplaying()) inside the onResume, but the app crashes when I resume from another activity. What am I doing wrong?

//global mediaplayer
MediaPlayer backgroundMusic;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);  
    loadBackgroundMusic();

}

private void loadBackgroundMusic() {

    //load mp3 into object and start it
    backgroundMusic = MediaPlayer.create(this,R.raw.backgrounmusic);
    backgroundMusic.setLooping(true);
    backgroundMusic.start();

}
        @Override
        protected void onPause() {
            super.onPause();
            backgroundMusic.release();

        }

        @Override
        protected void onResume() {
            super.onResume();
            loadBackgroundMusic();

        }

        @Override
        protected void onStop() {
            super.onStop();
            backgroundMusic.release();
        }

Upvotes: 0

Views: 2204

Answers (1)

tidbeck
tidbeck

Reputation: 2418

I'm not really sure about the behavior you want. As I see it, it's one of two:

  1. Music should be played only while my Activity is visible

    If this is the case, you should look closer on the documentation for the Activity Lifecycle. This will for example tell you that onResume() will also be called the first time the Activity is created.

    So the solution would be to start the music in onResume() and stop on onPause() or similar.

  2. After starting my activity once, music should be played even if i return to home screen

    In this case you really want a Service.

Upvotes: 1

Related Questions