Search code examples
javaandroidmedia-playerback

How to stop media player on back pressed regardless of whether it's playing or not?


@Override
public void onBackPressed(){
    super.onBackPressed();
    mp.release();
    overridePendingTransition(R.anim.anim, R.anim.anim2);
}

MediaPlayer is released when a sound is being played, however when a sound isn't being played it can't release anything and causes a null pointer. If I don't release it then it continues to play. It's a catch 22. How can I basically stop MediaPlayer regardless without any error?


Solution

  • release the media player in this manner

    if(mp!=null && mp.isPlaying()){
                 mp.release();
            }