0

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)
Community
  • 1
  • 1
thefriend
  • 339
  • 1
  • 6
  • 16

1 Answers1

0

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();
}
Tony Vu
  • 4,251
  • 3
  • 31
  • 38