android 三种定时器的写法


//两秒后执行
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
--todo
}
}, 2000);




-----------------------------------------


一、 使用Timer 和 TimerTask Timer timer
= new Timer(); MyTimerTask timerTask = new MyTimerTask(); timer.schedule(timerTask, 3000, 1); // 延迟3秒钟,执行1次 //timer.cancel();// 取消 class MyTimerTask extends TimerTask { @Override public void run() { //这里不能处理UI操作 // do something } } ------------------------------------------------------------------------ 二、采用Handler的sendMessageDelayed(Message, long) public void startAutoFlowTimer() { handler = new Handler() { @Override public void handleMessage(Message msg) { // do something Message message = handler.obtainMessage(0); sendMessageDelayed(message, 1000); } }; Message message = handler.obtainMessage(0); handler.sendMessageDelayed(message, 1000); } handler.removeMessages(0) //结束调用 --------------------------------------------------------------------------- 三、采用Handler的postDelayed(Runnable, long) 方法,这个实现比较简单一些: 1. Handler handler=new Handler(); Runnable runnable=new Runnable(){ @Override public void run() { // do something handler.postDelayed(this, 2000); //在这里实现每两秒执行一次 } }; handler.postDelayed(runnable, 2000);//启动,两秒后执行runnable. handler.removeCallbacks(runnable); //停止 --------------------------------------------------------------------------- //延迟执行 // 设置异步线程, Handler handler = new Handler() { public void handleMessage(Message msg) { // handle message switch (msg.what) { case 1: //ui 方法 } super.handleMessage(msg); } }; Message message = handler.obtainMessage(1); handler.sendMessageDelayed(message, 3000); // 发送message,3秒后隐藏提示框

转载自:http://www.cnblogs.com/weidingqiang/p/5569012.html

posted on 2016-07-05 12:34  随缘101  阅读(1407)  评论(0编辑  收藏  举报