简体   繁体   中英

How to run two asynchronous tasks one after another ?

I have tow asynctasks that I want that they run separately when I click on a button. I mean when the button is clicked the second one wont start until the first is already finished. By the way, i've tried to use :

if(task1.getStatus()==AsyncTask.Status.FINISHED){
task2.excecute();
}

But it doesn't work ...

Any help please?

Since HONEYCOMB, when using execute() , "tasks are executed on a single thread to avoid common application errors caused by parallel execution." So your AsyncTasks should run one after the other by default.

http://developer.android.com/reference/android/os/AsyncTask.html

How are you verifying that this isn't the case?

The if-statement does not wait until the condition is fullfilled. It just evaluates the condition, and if it's true, it executes the statement in the if block, otherwise the thread continues with the statement after the if block. Actually you have to wait for the condition.

The simplest method would be to just implement a wait loop:

while ( task1.getStatus()!=AsyncTask.Status.FINISHED )
{
    Thread.sleep( 10 );
}
task2.execute();

But this approach has the main drawback that the actual thread is blocking. Consider to use the Future framework introduced with java 6 to solve your problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM