Sagar Patil
Sagar Patil

Reputation: 1400

How to start video from where it stopped

I am using VideoView for playing video. If I go out of the application, while returning to the application ie in onResume() it should play the video from where it was stopped.

Upvotes: 4

Views: 3818

Answers (2)

Simon
Simon

Reputation: 14472

In onPause(), save the current position of the player, e.g. in shared preferences. In onResume(), retrieve the value and then use MediaPlayer.seekTo() to position.

http://developer.android.com/reference/android/media/MediaPlayer.html#seekTo(int)

@Override
protected void onPause() {

    Log.d(App.TAG, "onPause called");

    if(mMediaPlayer==null){
        Log.d(App.TAG, "Returning from onPause because the mediaplayer is null");
        super.onPause();
        return;
    }

    // the OS is pausing us, see onResume() for resume logic
    settings = getSharedPreferences(Dawdle.TAG, MODE_PRIVATE);
    SharedPreferences.Editor ed = settings.edit();
    mMediaPlayer.pause();
    ed.putInt("LAST_POSITION", mMediaPlayer.getCurrentPosition());  // remember where we are
    ed.putBoolean("PAUSED", true); 
    ed.commit();
    Log.d(App.TAG, "LAST_POSITION saved:" + mMediaPlayer.getCurrentPosition());

    super.onPause();
    releaseMediaPlayer();

}

@Override
public void onResume() {
    Log.d(App.TAG, "onResume called");

    try {

        if (mMediaPlayer==null){
            setupMediaPlayer();
        }

        // if we were paused (set in this.onPause) then resume from the last position
        settings = getSharedPreferences(Dawdle.TAG, MODE_PRIVATE);
        if (settings.getBoolean("PAUSED", false)) {
            // resume from the last position
            startPosition= settings.getInt("LAST_POSITION", 0);
            Log.d(App.TAG,"Seek to last position:" + startPosition);
        }

        mMediaPlayer.setDataSource(path);
        mMediaPlayer.setDisplay(holder);

        // this is key, the call will return immediately and notify this when the player is prepared through a callback to onPrepared
        // so we do not block on the UI thread - do not call any media playback methods before the onPrepared callback
        mMediaPlayer.prepareAsync();  

    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

private void startVideoPlayback() {
    Log.v(App.TAG, "startVideoPlayback at position:" + startPosition);
    mMediaPlayer.seekTo(startPosition);
    mMediaPlayer.start();
}

Upvotes: 2

Zelleriation
Zelleriation

Reputation: 2854

To get the current progress(check this in onPause):

long progress = mVideoView.getCurrentPosition(); 

To resume (in onResume):

mVideoView.seekTo(progress);

Upvotes: 3

Related Questions