4

I figured out if I exit an activity while is running the AsyncTask in the middle, and when I try to start that activity again, I will have to wait until the previous AsyncTask to finish before the new AsynTask starts. I tried both thread.sleep and systemclock.sleep and it gives me the same result. Which make sense because I guess the thread that I closed and opened are the same. Its there a way to just cancel the AsyncTask if the user exit an activity? Because then the second time the user enter the same activity he wouldn't have to wait until previous finishes. I tried asyntask.cancel(true) in onPause(), it doesn't work, same thing happened.

qwr qwr
  • 1,049
  • 4
  • 22
  • 46
  • 2
    Have a look here: http://stackoverflow.com/questions/4748964/android-cancel-asynctask-forcefully – newbyca Sep 05 '12 at 23:09
  • It works thanks! But how about the first part of my question? thread.sleep or systemclokc.sleep? – qwr qwr Sep 05 '12 at 23:15
  • I went ahead and submitted an actual answer for that specific part of your question, see below. – newbyca Sep 07 '12 at 00:51

1 Answers1

7

As I understand it, the only difference between Thread.sleep() and SystemClock.sleep() is that Thread.sleep() can be interrupted. That is, something like:

SystemClock.sleep(10*1000);

sleeps the calling thread for 10 seconds and that's that, you just have to wait. Whereas:

Thread.sleep(10*1000);

will also sleep the calling thread for 10 seconds. But if you have a reference to the sleeping thread from another thread, you now have the option of something like:

sleepingThread.interrupt();

which effectively wakes sleepingThread from its 10 second sleep.

In the context of your question, which is better for AsyncTask, I think it's still entirely up to your requirements. I don't know your exact code of course, but given your task's doInBackground is apparently doing some sleeping and given you want to be able to cancel your task at arbitrary times, Thread.sleep() might make more sense.

newbyca
  • 1,523
  • 2
  • 13
  • 25