1,Code example
private Timer mTimer;
private void startTimer(){
Log.d(TAG, "startTimer");
if(mTimer != null){
mTimer.cancel();
mTimer.purge();
mTimer = null;
}
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
Log.d(TAG, "schedule time");
}
}, 100, 1000);
}
private void stopTimer(){
Log.d(TAG, "stopTimer");
if(mTimer != null){
mTimer.cancel();
mTimer = null;
}
}private void testTimer(){ startTimer(); try{ Log.d(TAG, "sleep"); Thread.sleep(5000); }catch (Exception e){ } stopTimer();}个人理解1,在调用了Timer的calcel后就不在需要调用purge了,因为在Timer的calcel会直接clear队列里面的所有task,而purge是把队列里面状态为cancelled的移除,但是如果只是calcel掉单个timertask, 应该及时调用purge,防止内存泄漏;2,TimerTask就像一次性的筷子,用完就得扔掉,从队列里移除,置空,因为它只有4个状态,static final int VIRGIN = 0;static final int SCHEDULED = 1;static final int EXECUTED = 2;static final int CANCELLED = 3;Timer对他的状态不会进行重置,用完了代表这个任务已经完成并被遗弃;