Reputation: 1963
I tried plugging a SeekBar
into my video app, but it doesn't seem to ever reach the end of the bar. Here's the code:
videoSeekBar = (SeekBar) activity.findViewById(R.id.videoPlayerSeek);
videoDuration = player.getDuration();
videoSeekBar.setMax(videoDuration);
videoSeekBar.setProgress(0);
// Start lengthy operation in a background thread
new Thread(new Runnable() {
public void run() {
while (videoPlayProgress < videoDuration) {
videoPlayProgress = player.getCurrentPosition();
// Update the progress bar
handler.post(new Runnable() {
public void run() {
videoSeekBar.setProgress(videoPlayProgress);
}
});
}
}
}).start();
Then, I have an OnCompleteListener
attached to the MediaPlayer. When it is called,
player.getCurrentPosition()
returns 6209
player.getDuration()
returns 6592
Which can't be right. At this point, the slider status indicator isn't quite at the end of the slider bar, but there's a slight gap. The shorter the video's length, the bigger the gap.
Upvotes: 0
Views: 2254
Reputation: 1006819
First, consider <=
instead of <
.
More importantly, you do not need or want a busy-loop background thread for this. Go with something like:
Runnable r=new Runnable() {
public void run() {
videoSeekBar.setProgress(player.getCurrentPosition());
if (player.getCurrentPosition()<player.getDuration()) {
videoSeekBar.postDelayed(r, 33);
}
}
};
and somewhere call run()
on r
, when your video starts up. This will update the SeekBar
about 30 times per second.
Your current implementation is a foreground busy loop, posting thousands of messages onto the main application thread's queue, which will make your video playback performance worse and waste battery for no particular advantage.
This still might not get all the way to the end -- it's possible that the video will reach the end between the setProgress()
call and the if
test. The true test of it being at the end is the OnCompletionListener
, so just position the SeekBar
at the end at that point.
Upvotes: 3