tags:

views:

395

answers:

1

Hi all,

I have an AsyncTask object which starts executing when the activity is created and does stuff in the background (downloads upto 100 images). Everything works fine but there is this peculiar behavior which i'm not able to understand.

For eg: when the android screen's orientation changes then the activity is destroyed and created again. So I override the onRetainNonConfigurationInstance() method and save all the downloaded data executed in the AsyncTask. My purpose of doing this is to not have AsyncTask run each time activity is destroyed-created during orientation changes, but as i can see in my logs the previous AsynTask is still executing. (The data is saved correctly though)

I even tried to cancel the AsynTask in the onDestroy() method of the activity but the logs still show AsynTask as running.

This is really strange behavior and would really be thankful if someone can tell me the correct procedure to stop/cancel the AsynTask.

Thanks

A: 

AFAIK, you cannot stop an AsyncTask. I do not believe that the cancel() method will work if the task is already executing -- that will work if the task is waiting in a queue for a thread to free up.

CommonsWare
oh! I see.. then i guess i should just stop bothering about it.. i just wanted to save some bandwidth and internet usage.. too bad for me..
Raja
That is not correct, you can stop an AsyncTask. If you call cancel(true), an interrupt will be sent to the background thread, which may help interruptible tasks. Otherwise, you should simply make sure to check isCancelled() regularly in your doInBackground() method. You can see examples of this at code.google.com/p/shelves.
Romain Guy
I tried calling cancel(true), but it just returns false and the thread is still running in the background. Anyway I'll look into the shelves project, I appreciate your reply. Also since I'm testing while the device orientation changes so I think during the activity destruction-creation process the background threads are just being held as zombie threads.. I wouldn't know much about it, just my guess
Raja
@Romain Guy: You should have posted that as an answer rather than a comment so that you could gain rep. Or even better, a coment linking to an answer
Casebash