I got some concerns about AsyncTask that I could not clarify when reading the documentation.
My app main Activity runs several AsyncTask’s when it’s created. These AsyncTask’s mostly download data or retrieve data from the DB.
- If I go to a different Activity, will the AsyncTask’s created on
this one continue executing? Or will they stop working and leave the
task half done? If so, will they go on somehow when getting back to
this activity? - In order to start one of the activities from the
one that is running the AsyncTask’s, I need one of the AsyncTask’s
to be fully executed. How do I set this constraint? Could you show
me some sample code of this, please?
Thanks
Yes, it will continue to run. This can be a bit of a double-edged sword as it will typically also hold on to the Activity instance, causing it to live beyond its
onDestroy()callback, which is not ideal. If the task you are running does not have the same lifecycle needs as the Activity itself, it may be better placed into a Service.There are way too many ways to do this, many depending on the architecture of your application, to provide specific sample code…but here are a few higher level ideas. Since AsyncTask provides a simple callback method on the main thread (
onPostExecute) when the task execution is complete, you can set a flag at that point. Or perhaps simply check for the existence of whatever data the AsyncTask is retrieving from any code where the Activity would be launched. Again, a Service would provide good context for this, as multiple Activities could connect to the service and check the task status before moving forward.Another option, depending on your application, is to have the result of the task dumped into a ContentProvider. ContentProviders include a nice interface for notifying observers of changes without resorting to global Broadcast Intents.
HTH