android_计时器_定时循环任务


myTimerTask timerTask = new MyTimerTask();  
Timer timer = new Timer(true);  
timer.schedule(timerTask, 0, 1000);//定时每秒执行一次  

//定时任务,定时发送message  
private class myTimerTask extends TimerTask {   
    @Override  
    public void run() {  
		Message message = new Message();  
		message.what = 2;  
		myHandler.sendMessage(message);  //发送message
    }  
}  
  
//Handler可以通过message在各个线程间传递通信  
Handler myHandler = new Handler() {  
    // 接收到消息后处理  
    public void handleMessage(Message msg) {  
        switch (msg.what) {  
        case 1:  
			//UI操作
			break;  
        case 2:  
			//UI操作
            break;  
        }  
        super.handleMessage(msg);  
    }  
};  


//----------------------方法二-------------------------
//计时器实现
//调用,  
Message message = handler.obtainMessage(1);     
handler.sendMessageDelayed(message, 1000); //发送message


final Handler handler = new Handler(){ 
	public void handleMessage(Message msg){         // handle message 
		switch (msg.what) { 
		case 1: 
			//UI操作  

			Message message = handler.obtainMessage(1); 
			handler.sendMessageDelayed(message, 1000);     //发送message , 这样消息就能循环发送
		} 
		super.handleMessage(msg); 
	} 
};

你可能感兴趣的:(定时器,计时器,andriod)