Reputation: 24464
In the sample code for RandomMusicPlayer, reset()
is called right before release()
:
// stop and release the Media Player, if it's available
if (releaseMediaPlayer && mPlayer != null) {
mPlayer.reset();
mPlayer.release();
mPlayer = null;
}
Is this really necessary? Shouldn't the release
take care of everything that would possibly need reset
?
Upvotes: 1
Views: 4273
Reputation: 806
I know this question is really old, but i just wanted to post something that happened to me. In our Android app, we are playing some music from the internet using MediaPlayer on background threads. We started having tons of ANR's since then, and upon closer inspection, we found the issue: In our stopPlayer() method.
try {
if(mediaPlayer != null) {
if(mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
//mediaPlayer.reset(); --> this ****** line is causing ANR. Just release.
mediaPlayer.release();
mediaPlayer = null;
}
} catch (IllegalStateException e) {
FirebaseCrashlytics.getInstance().recordException(e);
}
So we learned the hard way that calling .reset() will ocasionally hang the entire app (even on a background thread) on some particular devices, i don't remember now which model or brand.
Upvotes: 0
Reputation: 33741
Shouldn't the release take care of everything that would possibly need reset?
Well, the MediaPlayer
can be quite tricky. You need to understand the states that a MediaPlayer can be in and the calls that are allowed in those different states. The state diagram and valid/invalid states are here - http://developer.android.com/reference/android/media/MediaPlayer.html#StateDiagram
The reason the code sample you provided calls reset()
is just a defensive measure to uninitialize the mediaPlayer
object to clean everything up properly. Strictly speaking, everything should be fine if you just call release()
, but i'm not 100% sure about that.
Upvotes: 0
Reputation: 2868
Per the documentation, release()
can be executed at any time. It is not necessary to call reset()
first, nor is it necessary to set the player to null
afterwards (GC should dispose of it in due time).
From the docs:
After release(), the object is no longer available.
That said, I've ran into a few issues with MediaPlayer and its documentation. It's a very complex object to work with and tends to be a little buggy at times especially after throwing an error (with no explanation of the error code anywhere to be found!)
Upvotes: 6