Android ExoPlayer onProgressChanged

ascallonisi picture ascallonisi · Feb 18, 2015 · Viewed 30.9k times · Source

How can I monitor progress changes on ExoPlayer?
I tried to implement a hidden MediaController and overriding setOnSeekBarChangeListener methods, but for now without success. I'm wondering if there is another way to listen to the ExoPlayer progress.

Answer

Ankit Aggarwal picture Ankit Aggarwal · Sep 30, 2016

I know this question is very old. But, I landed on this while implementing ExoPlayer. This is to help the others who do the same later on:)

So, I have followed the following methods to track progress of the playback. This is the way it is done in the ExoPlayer Google Docs. It works as needed.

Checkout PlayerControlView.java in Google ExoPlayer repository

updateProgressBar() is the function to update the SeekBar progress:

private void updateProgressBar() {
    long duration = player == null ? 0 : player.getDuration();
    long position = player == null ? 0 : player.getCurrentPosition();
    if (!dragging) {
        mSeekBar.setProgress(progressBarValue(position));
    }
    long bufferedPosition = player == null ? 0 : player.getBufferedPosition();
    mSeekBar.setSecondaryProgress(progressBarValue(bufferedPosition));
    // Remove scheduled updates.
    handler.removeCallbacks(updateProgressAction);
    // Schedule an update if necessary.
    int playbackState = player == null ? Player.STATE_IDLE : player.getPlaybackState();
    if (playbackState != Player.STATE_IDLE && playbackState != Player.STATE_ENDED) {
        long delayMs;
        if (player.getPlayWhenReady() && playbackState == Player.STATE_READY) {
            delayMs = 1000 - (position % 1000);
            if (delayMs < 200) {
                delayMs += 1000;
            }
        } else {
            delayMs = 1000;
        }
        handler.postDelayed(updateProgressAction, delayMs);
    }
}

private final Runnable updateProgressAction = new Runnable() {
    @Override
    public void run() {
        updateProgressBar();
    }
};

We call updateProgressBar() within updateProgressAction repeatedly until the playback stops. The function is called the first time whenever there is a state change. We use removeCallbacks(Runnable runnable) so that there is always one updateProgressAction to care about.

@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
  updateProgressBar();
}

Hope this helps!