在android中链接2个异步任务的正确方法

时间:2013-07-25 09:24:34

标签: java android multithreading android-asynctask chaining

我有两个异步任务,即任务1和任务2。

我需要先运行任务1,然后运行任务2,但我不想通过在任务1的onPostExecute实现中调用任务2来结合这两个;因为在其他情况下我将任务1作为独立使用。

我有办法定义两个异步任务,而不是彼此限制并在特定情况下链接它们吗?

非常感谢你的帮助。

2 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

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

我的机器上现在没有android SDK,所以我无法验证它。

答案 1 :(得分:-1)

您可以执行以下操作:

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);
}