0

My android app uses AsyncTask to download some data from a website.

But when I press the back button of my android device immediately after the activity starts, worker thread's onPostExecute method is called, which is wierd because android called onDestroy method prior to onPostExecute and the onPostExecute method runs on the main UIThread which I think doesn`t exist anymore.

Can anyone help me what I don`t understand?

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • 1
    The whole point of a AsyncTask is to run a process on a separate thread, so it will finish after the main UI thread's onDestroy because it's not the same thread. If you want to kill the task when you press back you can call yourTaskName.cancel() in the onBackPressed() method – the-ginger-geek May 29 '13 at 04:44

1 Answers1

2

An AsyncTask is basically executing what you want in the background as a separate thread from the UI. So when you quit the UI this doesn't necessarily mean that you've killed the AsyncTask. It will continue it's regular life cycle and end in onPostExecute. If you want to kill the AsyncTask too then you will have to call the cancel() function for the AsyncTask.

Know this though, you cannot actually kill an AsyncTask this will be done by Android itself. So you will have to wait a while till the current task is killed (if you call cancel()) for you to restart this particular AsyncTask.

You should also read up on onCancelled() methods. For more information checked out the documentation.

If I've made any mistakes, please correct me.

Karthik Balakrishnan
  • 4,353
  • 6
  • 37
  • 69
  • ok.Another question.My app show some data on the main activity and asynctask is downloading them.Here is scenario i don`t fully understand.While my asynctask is downloading the data,i press home button which calls onStop method and the activity is no longer visible. This means my asynctask can`t refresh the view on the activity?? – Mungunbat Enkhbayar May 29 '13 at 04:56
  • 1
    The only part as far as I've seen that is updated in the UI via the `asyncTask` while it's still executing `doInBackground` is a progress dialog. Which will be updated once you resume the activity. Until then it doesn't actually update the dialog but stores the progress. So, if it's at 4%, you go off and it's processed up to 10% and them you resume the activity it will display 10%. – Karthik Balakrishnan May 29 '13 at 07:21