简体   繁体   中英

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

...

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM