somidurlan
somidurlan

Reputation: 33

Not logic crash of ringtone app when I add onpause method on back button

I have app that uses media player for sounds. Code that I use to stop sounds when I press back button is:

@Override
public void onBackPressed() {
    super.onBackPressed();
    if (mp != null) {
        mp.reset();
        mp.release();
    }
   finish();
}

This code is working good, but if app suddenly gets interrupted, and sound is still playing it needs to stop, so I added the same thing in onPause method (same case if I add onStop method).

  @Override
protected void onPause() {
    super.onPause();
    if (mp != null) {
        mp.reset();
        mp.release();
    }
}

Now, when I press back, app crashes instead of going back (that worked before I added onPause method) onPause is working good, as sounds stops if I press Home button I'm getting this errors in logcat:

java.lang.RuntimeException: Unable to pause activity
java.lang.IllegalStateException

...

Upvotes: 0

Views: 54

Answers (1)

Eugene Laminskiy
Eugene Laminskiy

Reputation: 704

You can't reset MediaPlayer, that is released. Because after release the resource, that was used for playing sound is not available. You should change:

mp.reset();
mp.release();

to:

mp.release();
mp = null;

Upvotes: 1

Related Questions