android基本定时器和延时的用法,总结一下比较简洁的模式,方便简单地在程序中直接调用。
一、定时循环
1. handler.postDelayed+Runnable
首先创建一个Handler对象 Handler handler=new Handler();
然后创建一个Runnable对象 Runnable runnable=new Runnable(){ @Override public void run() { // TODO Auto-generated method stub //要做的事情,这里再次调用此Runnable对象,以实现每两秒实现一次的定时器操作 handler.postDelayed(this, 2000);
主线程中调用,使用PostDelayed方法,两秒后调用此Runnable对象 handler.postDelayed(runnable, 2000);
★ 关闭此定时器,可以这样操作 handler.removeCallbacks(runnable);
2. handler+timer+timeTask
首先创建一个Handler对象 Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1){ //do something super.handleMessage(msg);
然后创建一个Timer 对象 Timer timer = new Timer(); TimerTask timerTask = new TimerTask() { @Override public void run() { Message message = new Message(); message.what = 1; handler.sendMessage(message);
主线程中调用,使用schedule方法 //延时1s,每隔500毫秒执行一次run方法 timer.schedule(timerTask,1000,500);
3. Thread+handler
首先创建一个Handler对象 Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1){ //do something super.handleMessage(msg);
然后创建一个Timer 对象 class ScheduleThread extends Thread {//这里也可用Runnable接口实现 @Override public void run() { while (true){ try { //每隔1s执行一次 Thread.sleep(1000); Message msg = new Message(); msg.what = 1; handler.sendMessage(msg); } catch (InterruptedException e) { e.printStackTrace();
主线程中调用 new Thread(new ScheduleThread ()).start();
1. Handler的postDelayed方法:
new Handler().postDelayed(new Runnable() { @Override public void run() { //do something }, 1000); //延时1s执行
2. Timer + TimerTask方法:
timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { //do something },1000);//延时1s执行
3. Thread方法:
new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(1000);//延时1s //do something } catch (InterruptedException e) { e.printStackTrace();