这次为了完成学校里的一个任务,就做了一个简单的音乐播放器,当完成了基本功能后,在加个seekBar时使用了TimerTask,发现各种各样的bug.

一个bug印象最为深刻,每次当我开着音乐屏幕进入了锁屏状态的时候,再重新解锁,就会报出

java.lang.IllegalStateException:TimerTask is scheduled already

解决办法:

1)将timerTask以class的形式展现;

2)每次打开的时候先判断相应的实例是否为null,当!= null的时候 = null,并重新new一个;

3)很重要的一步,一定不要将 2)写在 onCreate里面,不然每次解锁后的效果依旧是bug,我一般写在onResume里面;

代码表示:


class Task extends TimerTask{


@Override

public void run() {

// TODO Auto-generated method stub

int current = MusicService.player.getCurrentPosition(); //获取音乐当前position

int duration = MusicService.player.getDuration(); //获取音乐总时长

//System.out.println(current+"----------------"+duration);

bar_music.setProgress(current);

bar_music.setMax(duration);

Message msg = new Message();

msg.what = ConstantUtil.CURRENT_TIME;

msg.arg1 = current;

msg.arg2 = duration;

handler.sendMessage(msg);

}

}

@Override

protected void onResume() {

super.onResume();

if (timer != null || task != null) {

timer = null;

task.cancel();

}

timer = new Timer();

task = new Task();

。。。

最后还有一个很重要的一项:

timer.scheduleAtFixedRate(task, 0, 200);

后面的那个200数字很重要,当然你不一定是200,有时候当这个数字表示的时间太小了的话

会导致在第一次打开seekBar时进度条不运行