user1166635
user1166635

Reputation: 2801

How to cancel TimerTask safely?

I have been developing the Android application and I use Timer and TimerTask objects for executing one task after particular time. But there is one problem - sometimes I need to cancel timertask, but if I do it that Android will cause an IllegalStateException. How can I cancel the task safely?

Upvotes: 3

Views: 463

Answers (1)

aioobe
aioobe

Reputation: 420951

You can't reuse TimerTasks.

The reason why you get IllegalStateException is (most likely) because you try to schedule a task that has previously been canceled.

To do it properly, i.e. to avoid the IllegalStateException, you need to create a fresh TimerTask each time you want to schedule it.

Upvotes: 4

Related Questions