Karen Forde
Karen Forde

Reputation: 1127

AsyncTask - How to wait for onPostExecute() to complete before using values it has updated

I have an API in one jar that uses AsyncTask to carry out some work in the background. I need to wait for the result to be returned and then do some more wok with this result.

I signal back to one class in onPostExecute() method and then the result is handled on the UI thread, but the handler needs to be defined as a callback in a different project altogether so I can't just do the work in the onPostExecute.

In the second project I need to wait for the AsyncTask to end AND for the response to be handled, then I need to display the results of the handler to a TextView in an activity in the second project.

Thread.sleep and using a CountDownLatch don't work because the handling is done in the UI thread. Is there any way to do such a thing?

Upvotes: 4

Views: 3552

Answers (1)

Alex Gitelman
Alex Gitelman

Reputation: 24722

If I understand correctly, you have AsyncTask in one jar and UI that needs to be updated in another jar. If you run them as one application it should not matter where they are located. Since you mentioned that some callback is involved you can just execute this callback in onPostExecute.

The following will be an approximate sequence of events

  • Activity from jar 2 creates async task and passes callback that knows how to update TextView as parameter to constructor
  • AsyncTask stores callback in instance variable
  • Activity executes AsyncTask
  • AsyncTask in onPostExecute calls method on callback with appropriate parameters
  • Callback updates TextView

Upvotes: 2

Related Questions