Lisa Anne
Lisa Anne

Reputation: 4595

Android: how to make sure an AsyncTask is terminated before I call another method?

The situation is very simple. I use an AsyncTask to retrieve a String from an HttpClient.

Now I need the String retrieved by the AsyncTask to call another method on that String,

therefore i need to make sure the AsyncTask has terminated before calling the other method.

How do I do this?

Thanks for any suggestion.

Upvotes: 3

Views: 1031

Answers (5)

G. Blake Meike
G. Blake Meike

Reputation: 6715

I suspect that you don't actually care whether it has "terminated" or not. I suspect you just care whether it's doInBackground method has completed. The simplest answer is that if either onPostExecute or onCancelled has been called, then doInBackground is done. If you need something more find grained, you'll have to do something like Phil describes:

private volatile boolean done;

//...

public boolean isDone() { return done; }

protected Result doInBackground(Params... params) {
    // ...
    done = true;
    return result;
}

Upvotes: 1

user2119701
user2119701

Reputation: 29

What ever you wanna do... Keep in mind if the main thread is blocked for 5 seconds, the user get a prompt asking if the user want to wait longer or exit the application.

Upvotes: 1

DigCamara
DigCamara

Reputation: 5578

If you absolutely need the value you might even want to try to launch a new thread (instead of an AsyncTask execution) and use the .join method to wait for it to exit.

It's usually frowned upon (you shouldn't be accessing http resources that way; you risk having an unresponsive app) but it would not be significantly different from the other suggested solutions.

Upvotes: 1

Phil
Phil

Reputation: 36289

Use a simple lock or mutex. Basically, add a variable and a getter in your AsyncTask:

public boolean locked;

public boolean isLocked(){
    return locked;
}

in your AsyncTask's onPreExecute method, add:

locked = true;

and in the onPostExecute method, add:

locked = false;

Any outside methods can then be placed into a loop such as:

MyTask foo = new MyTask();
foo.execute();
while (foo.isLocked())
{
    //wait, or sleep, or whatever
}
//here is where you execute code.

Upvotes: 2

amukhachov
amukhachov

Reputation: 5900

Just check if onPostExecute() already was called

Upvotes: 1

Related Questions