简体   繁体   English

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

[英]Proper way to chain 2 async tasks in android

I have two async tasks, namely task 1 and task 2. 我有两个异步任务,即任务1和任务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; 我需要先运行任务1,然后运行任务2,但我不想通过在任务1的onPostExecute实现中调用任务2来结合这两个; because I use task 1 as stand alone in other circumstances. 因为在其他情况下我将任务1作为独立使用。

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. 我现在在我的机器上没有android SDK,所以我无法验证它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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