Search code examples
androidandroid-mediaplayerandroid-videoview

Android MediaPlayer class throws java.lang.IllegalStateException after activity resumed


I'm trying to pause and resume VideoView with MediaPlayer in activity onPause() and onResume() methods, but in onResume() method MediaPlayer throws java.lang.IllegalStateException. I didn't release MediaPlayer but I think MediaPlayer automatically released after activity paused. How should I handle it?

private MediaPlayer mediaPlayer;

void prepareVideo() {
    videoView = new VideoView(context.getApplicationContext());
    String path = "android.resource://" + getPackageName() + "/" + 
    R.raw.my_video;
    videoView.setVideoPath(path);
}

videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mp) {
        mediaPlayer = mp;
        mediaPlayer.start();
    }
});

@Override
protected void onResume() {
    super.onResume();
    if (mediaPlayer != null) {
        mediaPlayer.start();
    }
}

@Override
protected void onPause() {
    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
        mediaPlayer.pause();
    }
    super.onPause();
}

The exception:

    Caused by: java.lang.IllegalStateException
    at android.media.MediaPlayer._start(Native Method)
    at android.media.MediaPlayer.start(MediaPlayer.java:1194)
    at co.myapp.app.reborn.myappTestActivity.onResume(myappTestActivity.java:370)
    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1259)
    at android.app.Activity.performResume(Activity.java:6347)
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3110)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3152) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1400) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:148) 
    at android.app.ActivityThread.main(ActivityThread.java:5530) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:734) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624) 

Solution

  • We just need to implement MediaPlayer.OnSeekCompleteListener interface and set MediaPlayer in onSeekComplete method.

    private MediaPlayer mediaPlayer;
    
    @Override
    public void onSeekComplete(final MediaPlayer mp) {
        mediaPlayer = mp;
    }