Ash
Ash

Reputation: 3532

AsynTask Determine When Finished

I'm wanting to return a Boolean value from a method which calls an AsyncTask to execute if order to find if it's finished. previously I called the .get() method (which was fine) but this halts all threads and I would like a progress dialog.

I'm toying with the idea of a for loop which sleep/waits say every 100ms and then checks getStatus() to see if it's equal to Status.FINISHED, but this seems like a poor idea.

Below is a small portion of code.

  jData.theTask.execute(url);


  if(jData.theTask.getStatus() == AsyncTask.Status.FINISHED) {
      if(!WebService.webServiceValid()) {
             showMessage();
             return false;
         }

      return true;
  }


  Log.d("fired", "false fired");
  return false;

The operation isn't going to be instantly complete, so it's just returning false and a race condition is occurring due to the operation has not finished. As mention above I could wrap it in a for loop to periodically check x amount of times, but I'm sure there's probably a better solution out there.

Many thanks

EDIT:

It seems that calling .execute() then .get() actually allows the UI to spawn my progress dialog box whilst waiting for the boolean from .get(long timeout, TimeUnit timeUnit). This is a solution to my problem, however I'll leave the question open until tomorrow incase anyone has comments regarding this.

Upvotes: 0

Views: 115

Answers (2)

Aswin Kumar
Aswin Kumar

Reputation: 5278

Move the contents of if(jData.theTask.getStatus()==AsyncTask.Status.FINISHED) {} block to inside onPostExecute()

Upvotes: 0

Arun George
Arun George

Reputation: 18592

The most appropriate place to know if a AsyncTask was completed is the method onPostExecute which is called after the doInBackground() execution. What you can do is return a Boolean variable from doInBackground() based on the execution of your background activity. When the control reaches onPostExecute() you can be assured that your background activity has completed.

The manner in which you are using the AsyncTask is inappropriate because after the call to execute() on a AsyncTask object the control returns to the next line of code.

Upvotes: 1

Related Questions