How to check if MediaPlayer () has been released?
I want to check if a MediaPlayer is released - how can I check it? I found that isPlaying throws an exception instead of false - it's hard to do it in a simple way.
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.release();
}
});
source to share
I don't think there is a way to do this through the MediaPlayer class itself.
The easiest way is to make a global variable that gets a value true
on creation and reset. It is installed on false
release.
boolean mIsPlayerRelease = true;
mediaPlayer = MediaPlayer.create(myContext, soundId); // ready to play
mIsPlayerRelease = false;
....
mediaPlayer.reset(); // ready to play again
mIsPlayerRelease = false;
....
mediaPlayer.release(); // can't be played until release.
mIsPlayerRelease = true;
EDIT:
You can fix the blocking problem by placing the creation in AsyncTask
and setting a variable on completion.
private class MediaCreator extends AsyncTask<Integer, Void, Boolean> {
WeakReference<Context> mCtx;
public MediaCreator(Context ctx) {
mCtx = new WeakReference(ctx);
}
@Override
protected Boolean doInBackgroind(Integer.... params) {
final Context ctx = mCtx.get();
if(ctx == null || params == null || params.length == 0) {
return false;
}
mediaPlayer = MediaPlayer.create(ctx, params[0];
}
@Override
protected void onPostExecute(Boolean success) {
if(success) {
mIsPlayerRelease = false;
} else {
mIsPlayerRelease = true;
}
}
}
You can put this class in any processing class mediaPlayer
. Start with
MediaCreator creator = new MediaCreator(myContext);
creator.execute(R.id.mySoundId);
The method doInBackground
will create and buffer the media player on a separate stream. It will return after creation and onPostExecute()
will be called on the main thread, giving a boolean value false
if the player was created.
source to share