1.使用handler做:
Handler handler = new Handler(); Runnable updateThread = new Runnable() { public void run() { // 获得歌曲现在播放位置并设置成播放进度条的值 if (mediaPlayer != null) { sb.setProgress(mediaPlayer.getCurrentPosition()); // 每次延迟100毫秒再启动线程 handler.postDelayed(updateThread, 100); } } };然后在onPrepare()里面post出去,在程序退出的时候销毁handler.removeCallback(runnable)
2.利用mediaPlayer.setOnBufferingUpdateListener方法做
也是在onPrepare里面添加下面的代码即可,把我注视的地方都去掉就可以显示了,
mediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
// int currentPosition, duration;
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
// currentPosition = mediaPlayer.getCurrentPosition();
// duration = mediaPlayer.getDuration();
// int time = ((currentPosition * 100) / duration);
// mProgressBar.setProgress(time);
mProgressBar.setSecondaryProgress(percent);
}
});
3.利用timer定时器任务:
- /*******************************************************
- * 通过定时器和Handler来更新进度条
- ******************************************************/
- TimerTask mTimerTask = new TimerTask() {
- @Override
- public void run() {
- if(mediaPlayer==null)
- return;
- if (mediaPlayer.isPlaying() && skbProgress.isPressed() == false) {
- handleProgress.sendEmptyMessage(0);
- }
- }
- };
- Handler handleProgress = new Handler() {
- public void handleMessage(Message msg) {
- int position = mediaPlayer.getCurrentPosition();
- int duration = mediaPlayer.getDuration();
- if (duration > 0) {
- long pos = skbProgress.getMax() * position / duration;
- skbProgress.setProgress((int) pos);
- }
- };
- };
- //*****************************************************
启动异步任务的地方最好也是放在 onPrepare里面