Android SeekBar控制视频播放进度实现过程讲解

  public class VideoActivity extends AppCompatActivity implements EdgeSensorView.MapDemo {

  private static final String TAG = "VideoActivity";

  private VideoView mVideoView;

  private SeekBar mSeekBar;

  private float curProgress;

  private float MAX_PROGRESS;

  private boolean isSeekBarProgress = false;

  private Handler handler = new Handler();

  // 播放过程,自动更新seekbar的进度

  private Runnable runnable = new Runnable() {

  public void run() {

  if (mVideoView.isPlaying()) {

  if (!isSeekBarProgress) {

  int current = mVideoView.getCurrentPosition();

  mSeekBar.setProgress(current);

  }

  }

  handler.postDelayed(runnable, 100);

  }

  };

  @Override

  protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_video);

  mSeekBar = findViewById(R.id.seekbar);

  mVideoView = findViewById(R.id.video_view);

  mVideoView.setVideoURI(Uri.parse("android.resource://"

  + getApplicationContext().getPackageName() + "/" + R.raw.vid_bigbuckbunny));

  // MediaController mediaController = new MediaController(this);

  // mVideoView.setMediaController(mediaController);

  mVideoView.requestFocus();

  mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

  @Override

  public void onPrepared(MediaPlayer mp) {

  mp.setLooping(true);

  MAX_PROGRESS = mVideoView.getDuration();

  mSeekBar.setMax((int) MAX_PROGRESS);

  Log.i(TAG, "onCreate: " + MAX_PROGRESS + "," + curProgress + "," + bitmaps.length);

  // 开始线程,更新进度条的刻度

  handler.postDelayed(runnable, 0);

  mVideoView.start();

  }

  });

  mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

  @Override

  public void onCompletion(MediaPlayer mp) {

  curProgress = 0;

  mSeekBar.setProgress(0);

  }

  });

  mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

  @Override

  public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

  }

  @Override

  public void onStartTrackingTouch(SeekBar seekBar) {

  isSeekBarProgress = true;

  if (mVideoView.isPlaying()) {

  mVideoView.pause();

  }

  }

  @Override

  public void onStopTrackingTouch(SeekBar seekBar) {

  int pro = seekBar.getProgress();

  mVideoView.seekTo(pro);

  if (!mVideoView.isPlaying()) {

  mVideoView.seekTo(pro);

  mVideoView.start();

  }

  isSeekBarProgress = false;

  }

  });

  }

  @Override

  protected void onResume() {

  super.onResume();

  }

  @Override

  protected void onPause() {

  super.onPause();

  }

  @Override

  protected void onDestroy() {

  super.onDestroy();

  handler.removeCallbacks(runnable);

  }

  private void updateSeekBarStatus(final boolean b) {

  runOnUiThread(new Runnable() {

  @Override

  public void run() {

  mSeekBar.setPressed(b);

  }

  });

  }

  }