Search code examples
androidmedia-playerandroid-mediaplayermedia

Handle the seekTo function of media player in android


There is a video activity, I need to handle:

1) when the first time enter the activity, get the position from intent and play the video

2) keep the same position after rotate

Here is the code to handle first requirement

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.video_full_screen);
    ButterKnife.bind(this);

    if (getIntent() != null) {
        video_url = getIntent().getStringExtra("video_url");
        pos = (int)getIntent().getLongExtra("time", 0);
    }

    player.setOnPreparedListener(this);
    player.setVideoURI(Uri.parse(video_url));
}

@Override
public void onPrepared(MediaPlayer mp) {
    player.seekTo(pos);
    player.start();
}

Here is the code to handle second requirement

@Override
    protected void onSaveInstanceState(Bundle outState)
    {
        outState.putInt("time", (int)player.getCurrentPosition());
        player.pause();
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState)
    {
        int last_pos = savedInstanceState.getInt("time");
        player.seekTo(last_pos);
        player.start();
        super.onRestoreInstanceState(savedInstanceState);
    }

The problem is the handling is conflict to each other.

If first time enter progess is 10s , when I play at e.g. 30s and rotate , it still go to 10s instead of 30s.

It is caused by the seekTo(pos) at the onPrepared function but I can not remove that as it handle the first requirement.

How to fix that? Thanks for helping.


Solution

  • Rotating the screen calls onDestroy(). Are you saving the time progress in onDestroy()? For more info on android life cycle see: https://androidcookbook.com/Recipe.seam?recipeId=2636