I have Runnable that runs in Thread in a MediaPlayer. When i press back I get an IllegalStateException.
Here is the Runnable:
mp is 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 method:
@Override
public void onDestroy(){
super.onDestroy();
mp.release();
}
Error log:
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)
I suspect that you called mp.pause()
in OnPause()
method of this activity. So when you clicked back button, MediaPayer went into pause status. However since your Runnable is called asynchronous, so it will call mp.getDuration() in an invalid state. To fix this, please add in the check:
if (mp.isPlaying()) {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.