我知道以前有人问过这个问题,但我无法在代码中实现它。如果我捕获,如何再次重试try-catch块?
if(mediaPlayer!=null){
try {
mediaPlayer.start();
songEnded = 0;
} catch(IllegalStateException e) {
// media player is not initialized
//TRY AGAIN
}
}
我认为最好的办法是将其封装在while循环中,并在while环路中添加一个条件来检查媒体播放器是否已启动。
例如:
void playMediaPlayer() {
MediaPlayer mediaPlayer = new MediaPlayer();
while (!mediaPlayer.initialized) {
try {
mediaPlayer.start();
mediaPlayer.initialized = true;
} catch (IllegalStateException ignored) {
// optionally wait some time before trying again
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class MediaPlayer {
boolean initialized = false;
public void start() throws IllegalStateException{
}
}