SpoocyCrep
SpoocyCrep

Reputation: 614

Mediaplayer when coming back to activity

This is my onPause:

@Override
protected void onPause() {
    try{
    if(m.isPlaying()){
        m.pause();
    }
    }
    catch(Exception e){

    }
    super.onPause();
}

This is my onStop:

@Override
protected void onStop() {
    try{
    if(m!=null){
        m.stop();
        m.release();
    }
    }
    catch(Exception e){

    }
    super.onStop();
} 

And this is my onResume:

@Override
protected void onResume() {
    try{
        if (m == null) {
                m.reset();
                m = MediaPlayer.create(this, R.raw.menu);
                m.start();
        }
        else{
            m.start();
        }
    }
    catch(Exception e){

    }
    super.onResume();
}

There is a mediaplayer on my activity that plays, My goal is that when a new activity opens it will stop, and when there is a back press the music will reset and start playing all over again. This code only stops the music on new activity, when I come back there is no music. Why?

Upvotes: 0

Views: 314

Answers (1)

sschrass
sschrass

Reputation: 7156

 if (m == null) {
     m.reset();
     m = MediaPlayer.create(this, R.raw.menu);
     m.start();
 }

here you are starting an uninitialised MediaPlayer instance. You need to prepare it first before calling start(). Therefore you should get an IllegalStateException. here is a statediagram for reference.

Upvotes: 1

Related Questions