Recently I've been learning Android from Beginning Android games when I came across this code:
MediaPlayer mediaPlayer;
boolean isPrepared = false;
public AndroidMusic(AssetFileDescriptor assetDescriptor) {
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(assetDescriptor.getFileDescriptor(),
assetDescriptor.getStartOffset(),
assetDescriptor.getLength());
mediaPlayer.prepare();
isPrepared = true;
mediaPlayer.setOnCompletionListener(this);
} catch (Exception e) {
throw new RuntimeException("Couldn't load music");
}
}
public void dispose() {
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.release();
}
public boolean isLooping() {
return mediaPlayer.isLooping();
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public boolean isStopped() {
return !isPrepared;
}
public void pause() {
if (mediaPlayer.isPlaying())
mediaPlayer.pause();
}
public void play() {
if (mediaPlayer.isPlaying())
return;
try {
synchronized (this) {
if (!isPrepared)
mediaPlayer.prepare();
mediaPlayer.start();
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void setLooping(boolean isLooping) {
mediaPlayer.setLooping(isLooping);
}
public void setVolume(float volume) {
mediaPlayer.setVolume(volume, volume);
}
public void stop() {
mediaPlayer.stop();
synchronized (this) {
isPrepared = false;
}
}
public void onCompletion(MediaPlayer player) {
synchronized (this) {
isPrepared = false;
}
}
}
I'm very confused as to why we need to synchronize things here. Will there be more than one thing accessing these synchronized blocks? The book states, " The method OnCompletionListener.onCompletion() might be called in a separate thread, and since we set the isPrepared member in this method, we have to make sure that it is safe from concurrent modifications. " CallBacks are new to me, but I assume that when the MediaPlayer finishes, onCompletion is called. How will this onCompletion be called from a separate thread? Won't it be called on the thread that's executing this class? Eg, Thread 1 is executing play() and eventually the file ends, so onCompletion() is called on Thread 1. How will this be called on Thread 2? The synchronization on onCompletion() confuses me most, as with the other ones I somewhat understand that a different thread(UI thread) might edit the value of isPrepared in stop(), so that needs to be synchronized. The book's explanation further confuses me. How does this synchronization work, and what purpose does it serve?