I start by loading a Media player into a composition class:
public class MediaPlayerWURI {
private final MediaPlayer mediaPlayer;
final Uri uri;
final ActivityMain activityMain;
boolean isPrepared = true;
MediaPlayerWURI(ActivityMain activityMain, MediaPlayer mediaPlayer, Uri uri){
this.activityMain = activityMain;
this.mediaPlayer = mediaPlayer;
this.uri= uri;
mediaPlayer.setOnPreparedListener(null);
mediaPlayer.setOnErrorListener(null);
mediaPlayer.setOnPreparedListener(new MOnPreparedListener(this));
mediaPlayer.setOnErrorListener(new MOnErrorListener());
}
public void prepareAsync(){
isPrepared = false;
mediaPlayer.prepareAsync();
}
public void start(){
mediaPlayer.start();
}
public void stop(){
isPrepared = false;
mediaPlayer.stop();
}
class MOnPreparedListener implements MediaPlayer.OnPreparedListener{
final MediaPlayerWURI mediaPlayerWURI;
public MOnPreparedListener(MediaPlayerWURI mediaPlayerWURI){
this.mediaPlayerWURI = mediaPlayerWURI;
}
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayerWURI.isPrepared = true;
}
}
class MOnErrorListener implements MediaPlayer.OnErrorListener {
public MOnErrorListener(){
}
@Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
activityMain.releaseMediaPlayers();
return false;
}
}
}
The media player passed in is created with MediaPlayer.create(getApplicationContext())
and is started successfully.
The following code do not trigger onPrepared()
and gets stuck in a loop.
mediaPlayerWURI.stop();
mediaPlayerWURI.prepareAsync();
while (!mediaPlayerWURI.isPrepared) { }
mediaPlayerWURI.start();
I have tried prepareAsync()
on another thread:
executorService.submit(new Runnable() {
@Override
public void run() {
mediaPlayerWURI.prepareAsync();
}
});
My guess is it is a threading issue, but I am not sure how to handle this, or if it even is a threading issue. My understanding is that the MediaPlayer is preparing in another thread and that the loop shouldn't prevent it from calling on prepared. I am not sure what thread onPrepare()
is ran on, but from the above, I think it means the main thread is supposed to run onPrepare()
and is waiting for the loop to end.
Also, I am getting weird behavior where onPrepared()
is being called after the construction of the MediaPlayer. Is that normal? My assumption is that onPrepared()
is called when setOnPrepared()
is called on a prepared MediaPlayer. This means the listener is attached.