Android计时器

private Handler handler  = new Handler(){
	    public void handleMessage(Message msg) {
	        super.handleMessage(msg);
	           //满足条件要执行的内容
	        if(msg.what == 1&&msg.arg1 == 0){
	            //
	        	Log.v(TAG, "计时器");
		    	if(todoNum != 0){
	    		todoDocNumTV.setVisibility(View.VISIBLE);
	    		todoDocNumTV.setText(todoNum+"");
	    		isRefresh = 1;
	    	}
	        }
	    }
	};
	 
	 
	private Timer timer = new Timer(true);
	 
	//任务
	private TimerTask task = new TimerTask() {
	  public void run() {
	    Message msg = new Message();
	    msg.what = 1;
	    msg.arg1 = isRefresh;
	    handler.sendMessage(msg);
	  }
	};

启动计时器
//启动定时器
timer.schedule(task, 0, 1*1000);


当我想停止计时器再重启是遇到一个问题,报错ava.lang.IllegalStateException: TimerTask is scheduled already
发现每根TimerTask只能执行一次schedule
所以只能在重启之前清空之前的任务并重新赋值,然后再启动
if(task != null){
			task.cancel(); //将原任务从队列中移除
		}
		task = new TimerTask() {
			  public void run() {
			    Message msg = new Message();
			    msg.what = 1;
			    msg.arg1 = 0;
			    handler.sendMessage(msg);
			  }
			};
		//启动定时器
		timer.schedule(task, 0, 1*1000);

你可能感兴趣的:(android)