Answer the question
In order to leave comments, you need to log in
Android: How to gracefully wait for an AsyncTask to complete after cancel()?
Situation: An Activity starts an AsyncTask that should download a document from the web and parse it. There is a "cancel" button that should end the task by calling cancel(). Plus, the task should be completed from onPause (roughly speaking, if the Activity is closed).
Since the task may not immediately check isCancelled() after cancel() (for example, due to waiting for the document to load), a situation may arise when the Activity has already closed, but the task is still running and calls the methods of the Activity from onCancelled (for example, to save the state on moment of cancellation or show a message). It will turn out badly, the application will fall.
To avoid this, I would like to carefully wait for the task to complete after cancel(). AsyncTask.get() is not suitable - it just throws a CancellationException in this situation. Accordingly, we need some other way to wait for the completion of the AsyncTask without leaving onPause or, alternatively, tell the task that it is no longer possible to pull the Activity methods from onCancelled (and if the cancellation was by the button, then it is possible and necessary). So far, there is only one idea - to pull the Activity through static methods that will check if it is available (in onCreate / onResume remember the static pointer to the Activity, in onPause reset it to null, in static methods, check).
But this method somehow smells bad. It is hard to believe that something more standard is not provided for this case. Can someone tell me where to look?
By the way, the situation is aggravated by the fact that sometimes the last onProgressUpdate is processed after onCancelled, and it definitely must have access to the Activity.
Answer the question
In order to leave comments, you need to log in
Your AsyncTask stores a reference to an object of the Activity class, as an option, you can delete this reference when the Activity ends (in onDestroy). Those. you can add a method to the task (ala removeLinkActivity), in which you can nullify the link to the Activity, and in those places where you use this activity, simply check for null, i.e. if not null, then we call the method, if null, then no.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question