1. 程式人生 > >android使用mediaPlayer顯示視訊時,丟擲java.lang.IllegalStateException異常

android使用mediaPlayer顯示視訊時,丟擲java.lang.IllegalStateException異常

使用Mediaplayer播放視訊時,自定義了進度條顯示進度,一次需要使用run方法來實時監測視訊播放的位置,程式碼如下:Runnable runnable = new Runnable() {

@Override
public void run() {
if (player != null) {
int pos = player.getCurrentPosition();
if (pos > 0) {
int duration = player.getDuration();
int ss = (int) (player.getCurrentPosition() * 100)
/ duration;
progress.setProgress(ss);
video_time.setText(TimerUtils.formatTimes(player
.getCurrentPosition()));
if (pos == duration) {
player.pause();
btn_player
.setBackgroundResource(R.drawable.bt_view_play);
}
} else {
video_time.setText("00:00");
progress.setProgress(0);
}
}
view_handler.postDelayed(runnable, 1000);
}
};

但是在退出該activity時,總是會報錯java.lang.IllegalStateException,而位置則是指向 player.getCurrentPosition(),

在onDestroy方法中relese掉了mediaplayer,但是仍會報錯;後來發現,當退出該activity時,將其destroy掉了,但是隻是釋放掉player是不夠的,同時還要增加判斷

                if (player != null) {
player = null;
}

將mediaplayer設定為空,runnable 中的內容就不會在退出activity時繼續執行,而引起異常了。