简体   繁体   中英

Proper way to chain 2 async tasks in android

I have two async tasks, namely task 1 and task 2.

I need to run task 1 first and then task 2 just after but I do not want to couple the two by calling task 2 in the onPostExecute implementation of task 1; because I use task 1 as stand alone in other circumstances.

I there a way to have the two async tasks defined without being bounded to each other and chain them in specific circumstances?

Thank you very much for your help.

You can try something like this:

final Executor directExecutor = new Executor() {
  public void execute(Runnable r) {
    r.run();
  }
};
AsyncTask.execute(new Runnable() {
  task1.executeOnExecutor(directExecutor, params1);
  task2.executeOnExecutor(directExecutor, params2);
});

I don't have android SDK on my machine now, so I can't verify it.

You can do the following:

YourAsyncClass1 thread1 = new YourAsyncClass1();
thread1.execute(inputArgument1);

    try {
        outputResult1 = thread1.get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
if(outputResult1 == true /*Or expected result*/){
  YourAsyncClass2 thread2 = new YourAsyncClass2();
  thread2.execute(inputArgument2);
}

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