tags:

views:

509

answers:

3

I have an AsyncTask that acts as a countdown timer for my game. When it completes the countdown it displays the out of time end screen and it also updates the timer displayed on the screen. Everything works fine, except I need to be able to pause and resume this when the pause button in the game is pressed.

If I cancel it and try to re-execute it, it crashes with an IllegalStateException. If I cancel it and instantiate a new AsyncTask in its place the old one begins to run again and the new one runs at the same time.

Is there a way to cancel/pause the timer and restart it using AsyncTasks or is there a different way I should be going about doing this?

+1  A: 

I have an AsyncTask that acts as a countdown timer for my game.

That is not a good use of AsyncTask. AsyncTasks should do work and be done, not try hanging around. For a countdown timer, use postDelayed() -- you don't even need a background thread. Or, use CountDownTimer.

If I cancel it and try to re-execute it, it crashes with an IllegalStateException.

The documentation states: "The task can be executed only once (an exception will be thrown if a second execution is attempted.)"

CommonsWare
Thanks for the info. Looking into postDelayed() and Handlers I think I found a suitable solution.
Matt Swanson
A: 

Hello,

I have a similar problem, i.e. I need to pause/resume a task that's running in the background with AsyncTask. I'm streaming audio files from a web server and I don't want the UI to be dead in the mean time. I want the user to be able to pause and resume this audio.

  1. Is it possible to pause/resume an AsyncTask?
  2. If not, is there another way to do what I want?

Thank you in advance. I hope you can help me.

Cheers, Jalal

JaySS
This should really be a new question. But use a service.
alexanderblom
A: 

To JaySS,

  1. I don't think AsyncTask can be resumed. As to pause, I've tried to use AsyncTask.cancel(true) to stop a task which is running. After cancel I use AsyncTask.isCancelled() to check whether it's cancelled or not. It returned true; however, the AsyncTask is still running.
miaomiao