当我们需要每隔一段时间执行一个任务的时候,就需要使用TimerTask了,下面是入门的例子,
值得注意的是Timer、TimerTask,cancel之后就需要重新声明一个对象,否则会报错的哦~
package zhexian.app.myapplication; import android.util.Log; import java.util.Timer; import java.util.TimerTask; /** * Created by kimmy on 2015/9/30. */ public class TimerTaskDemo { /** * 任务延时执行 */ private static final int DELAY_DURATION = 0; /** * 任务执行间隔 */ private static final int LOOP_DURATION = 100; private Timer timer; private TimerTask mTimerTask; public void start() { if (timer != null) timer.cancel(); timer = new Timer(); if (mTimerTask != null) mTimerTask.cancel(); mTimerTask = new TimerTask() { @Override public void run() { Log.d("定时触发器", "mTimerTask"); } }; timer.schedule(mTimerTask, DELAY_DURATION, LOOP_DURATION); } public void stop() { if (timer != null) timer.cancel(); if (mTimerTask != null) mTimerTask.cancel(); } }