Android 计时器及TimerTask is scheduled already的Bug处理
Android 计时器开发需要学习两个知识点:1.Timer 2.TimerTask。需要注意的是,每次调用Timer时,必须新实例化一个TimerTask对象(参考黑崎焚天解决了我的这个Bug),那就要求Timer执行完,释放掉当前TimerTask.实现代码如下:
public class HXTimer { private int recLen=15; //倒计时时长 private TimerTask timerTask=null;//定时任务 private Handler mHandler=null; private Timer timer=null;//计时器 public HXTimer(int recLen, long delay, long period, Handler mHandler){ this.recLen=recLen; this.mHandler=mHandler;; timer=new Timer(); getTimerTastInstance(); timer.schedule(timerTask,delay,period); } //获取一个定时任务实例 private void getTimerTastInstance(){ timerTask=new TimerTask() { @Override public void run() { recLen--; if(recLen <= 1){ timer.cancel(); } if(mHandler!=null) { Message message = new Message(); Bundle bundle = new Bundle(); bundle.putInt("recLen", recLen); message.setData(bundle); message.what = 2000; mHandler.sendMessage(message); } } }; } public void cancel(){ if(timerTask!=null) { timerTask.cancel(); timerTask = null; } if(timer!=null) { timer=null; } } }