Search code examples
androidmedia-playerondestroy

releasing mediaplayer when calling OnDestroy forces exit when backplayer pressed


I have an app that plays audio after taking the user through a couple of views. At first all worked fine except when the backbutton is pressed while audio is playing at which point the app closed but the audio carried on. After researching, I put in the OnDestroy method and released the mediaplayer which now stops when the back button is pressed during the audio play.

However now when the back button is pressed during one of the previous views before the mediaplayer is started I get a force close message and the logcat says Unable to Destroy Activity - I assume because there is no mediaplayer for it to release? Does anyone know what is going on?

I have tried an if statement to super.OnDestroy only when media is playing but this has no effect.


Solution

  • If you try to release your Mediaplayer but that you didn't initialize it if the user is not playing a song it makes sense that you're getting an Exception.

    As often, verifying if your value is null or not is probably the key. One more thing : don't handle this case in onDestroy because it is not guaranteed to be called, prefer onStop to it if possible.