How to safely cancel TimerTask?

I am developing an application for Android, and I use objects Timerand TimerTaskto complete one task after a certain time. But there is one problem - sometimes I need to cancel the timertask, but if I do this, then Android will call IllegalStateException. How can I cancel a task safely?

+3
source share
1 answer

You cannot reuse TimerTasks.

The reason you get IllegalStateException(most likely) is because you are trying to schedule a task that was previously canceled.

To do it right, i.e. To avoid IllegalStateException, you need to create a new TimerTaskone every time you want to plan it.

+4

All Articles