我有Runnable在MediaPlayer中的Thread中运行。当我按回来时,我得到一个IllegalStateException。
这是Runnable:
mp是MediaPlayer
private Runnable mUpdateTimeTask = new Runnable() {
public void run() //This line is AndroidBuildingMusicPlayerActivity.java:318
{
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
// Displaying Total Duration time
songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));
// Updating progress bar
int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
//Log.d("Progress", ""+progress);
songProgressBar.setProgress(progress);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
}
};
OnDetroy方法:
@Override
public void onDestroy(){
super.onDestroy();
mp.release();
}
错误日志:
FATAL EXCEPTION: main
java.lang.IllegalStateException
at android.media.MediaPlayer.getDuration(Native Method)
at com.androidhive.musicplayer.AndroidBuildingMusicPlayerActivity$9.run(AndroidBuildingMusicPlayerActivity.java:318)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
我怀疑您在此活动的mp.pause()
方法中调用了OnPause()
。因此,当您单击后退按钮时,MediaPayer进入暂停状态。但是,由于Runnable被称为异步,因此它将在无效状态下调用mp.getDuration()。要解决此问题,请添加支票:
if (mp.isPlaying()) {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
}