0

I have read that an AsyncTask keeps running even if the calling activity has stopped. Keeping this in mind, I am trying to understand the working of onTaskCompleted. onTaskCompleted is usually called from onPostExecute() of the AsyncTask and if the calling activity still exists, everything is good. But what if the calling activity has stopped? Will this result in a crash of the app?

This question came to me because I was thinking of updating some global variables or UI components in the calling activity on the result of the AsyncTask. Is this a good idea? Won't this also result in a crash?

Thanks.

Sid
  • 1,270
  • 2
  • 15
  • 30
  • This link might help you a little bit. http://stackoverflow.com/questions/18479366/updating-ui-thread-from-asynctask-in-public-class – Mocanu Bogdan Oct 03 '15 at 17:33
  • hii @Sid if the calling activity has stopped, then AsyncTask will not die. It will go on living until it completes.And when it completes, the AsyncTask won't update the UI of the new Activity. Indeed it updates the former instance of the activity that is not displayed anymore. This can lead to an Exception of the type java.lang.IllegalArgumentException: View not attached to window manager if you use findViewById() to retrieve a view inside the Activity. – Awadesh Oct 03 '15 at 17:43
  • @MocanuBogdan That isn't solving my problem. It is a different problem. – Sid Oct 03 '15 at 17:48
  • @Awadesh So, are you saying that updating the UI in the onTaskCompleted function is not a good idea at all? But there are so many posts which use this method to update the UI. Are all those exposed to the risk of throwing the above mentioned exception in case the activity stops? Also, what if onTaskCompleted() updates some global variable? Will that cause also cause the app to crash with any exception? – Sid Oct 03 '15 at 17:49
  • @Sid if you are updating the UI of destroyed activity then there is exception because view does not exist otherwise its fine. – Awadesh Oct 03 '15 at 18:07

0 Answers0