How To Implement A Mediaplayer Restart On Errors In Android?
Solution 1:
Overview
I ran into a similar issue and based on the documentation it indicates that all you need to do is reset your media player:
In order to reuse a MediaPlayer object that is in the Error state and recover from the error, reset() can be called to restore the object to its Idle state.
What you are currently doing is stopping and releasing (mplayer.stop()
and mplayer.release()
) a media player that is in the Error state. This should be causing something like an IllegalStateException to be raised. If it's not throwing an error you would still be trying to start a song in a null object. Instead of calling stop and release then setting the variable to null you should be using the mplayer.reset()
function.
Another option would be to initiate a new media player but the documentation details the subtle difference between a newly instantiated MediaPlayer object and one that has had reset()
called on it.
Reset after Error
Based on this information something like the following should fix your issue:
publicbooleanonError(MediaPlayer mp, int what, int extra)
{
Log.e(getPackageName(), String.format("Error(%s%s)", what, extra));
playlist="ERROR";
if(what == MediaPlayer.MEDIA_ERROR_SERVER_DIED)
mp.reset();
elseif(what == MediaPlayer.MEDIA_ERROR_UNKNOWN)
mp.reset();
// Deal with any other errors you need to. // I'm under the assumption you set the path to the song// and handle onPrepare, start(), etc with this function
playSong(getApplicationContext(),currenturl);
mplayer.setOnErrorListener(this);
mplayer.setOnCompletionListener(this);
mplayer.setOnPreparedListener(this);
returntrue;
}
See media player constant documentation for a list of potential errors.
Setting Error Listener
As for setting the error listener, here is how I've implemented it in the past:
publicclassMediaPlayerActivityextendsActivityimplementsOnCompletionListener,
OnPreparedListener, AnimationListener, OnErrorListener{
private MediaPlayer mediaPlayer;
@OverridepublicbooleanonError(final MediaPlayer arg0, finalint arg1, finalint arg2) {
// Error handling logic herereturntrue;
}
protectedvoidonResume(){
super.onResume();
// do some onResume logic
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
// finish on resume and start up media player
}
}
I then handle loading up the media player in another function initiated by onResume().
Post a Comment for "How To Implement A Mediaplayer Restart On Errors In Android?"