2
votes

I'm trying to pause a video when Activity's onPause() is called. And then resume it and keep playing at the moment it was left when resuming the activity.

I've read many posts on how to achieve this and to sum up, I've read that I should call mediaPlayer.pause() in Activity's onPause(), and mediaPlayer.play() in Activity's onResume(). Seems simple, but I keep getting IllegalStateException in onResume: mediaPlayer.play()

This is where I'm setting mediaplayer and videoview:

videoView.setMediaController(mediaController);
        videoView.setVideoURI(videoUri);
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                // Pass MediaPlayer to control playback speed
                mediaController.setMediaPlayer(mp);
                mp.start();
                mediaPlayer = mp;
                hideProgressBar();
            }
        });

This code is called after I get videoUri from an API call, this call is done in onCreate().

And in onResume() onPause():

    @Override
protected void onResume() {
    super.onResume();

    if (mediaPlayer != null) {
        mediaPlayer.start();
    }

}

@Override
protected void onPause() {
    super.onPause();

    if (mediaPlayer != null ) {
        mediaPlayer.pause();
    }
}
1
where do you instanciate the mediaplayer object? Is it not getting created every time the activity gets created? - Sebastian Breit
@Perroloco I get mp from onPrepared() as shown above, and I assign that mp to mediaPlayer which is a class attribute, to keep reference of mp so I can call it from onPause and onResume. - IRPdevelop

1 Answers

2
votes

Ok, I figured it out. In onPreparedListener() I add a validation to check if the app was previously paused or not. If it was paused, I use seekTo(), otherwise I just play the video from the beginning.

videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                // Pass MediaPlayer to control playback speed
                mediaController.setMediaPlayer(mp);
                mediaPlayer = mp;
                if (resumedActivity) {
                    mp.seekTo(pausedMilliSec);
                }
                mp.start();
                hideProgressBar();
            }
        });

And in onPause():

@Override
protected void onPause() {
    super.onPause();

    if (mediaPlayer != null) {
        resumedActivity = true;
        pausedMilliSec = mediaPlayer.getCurrentPosition();
    }
}