Java. Lang. An IllegalStateException Task already scheduled or cancelled the reason is mainly because the Timer and TimerTask is one-time consumables, When the task is scheduled again after cancle is called, the new timer and task need to be renewed.

  • Solutions are as follows:

  • Method one:

After calling the cancle method of Timer, you need to re-new the new Timer and task. The following

Private void initCursorTimer() {mCursorTimerTask = new TimerTask() {@override public void run() {// Achieve blinking effect through intermittent cursor display isCursorShowing = ! isCursorShowing; postInvalidate(); }}; mCursorTimer = new Timer(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); initCursorTimer(); / / start time task, time to refresh the implementation cursor blink mCursorTimer. ScheduleAtFixedRate (mCursorTimerTask, 0, mCursorDuration); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mCursorTimer ! = null) { mCursorTimer.cancel(); mCursorTimer.purge(); mCursorTimer = null; }}Copy the code

It is important to note that the Purge method also needs to be called when the cancle method of timer is called

  • Method 2:

When the TimerTask cancle method is called, there is no need to create a new timer, that is, all tasks share the same timer.

@Override protected void onAttachedToWindow() { super.onAttachedToWindow(); MCursorTimerTask = new TimerTask() {@override public void run() {iscursortask =! isCursorShowing; postInvalidate(); }}; / / start time task, time to refresh the implementation cursor blink mCursorTimer. ScheduleAtFixedRate (mCursorTimerTask, 0, mCursorDuration); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mCursorTimerTask ! = null) { mCursorTimerTask.cancel(); mCursorTimerTask = null; }}Copy the code
  • twocancleThe difference in methods isTimerTaskClass orTimerClass,cancelMethods are used to clear tasks from the task queue. Although both are tasks in the clear task queue, there are some differences:TimerTaskIn the classcancelThe method focuses on clearing itself from the task queue, while other tasks are not affectedTimerIn the classcancelThe method is to empty all tasks in the task queue.

The Purge method is used to free up memory references. The Purge method checks for tasks marked canceled in the Timer queue and sets the reference to it to NULL.