繁体   English   中英

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

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

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

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

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

非常感谢您的帮助。

你可以尝试这样的事情:

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,所以我无法验证它。

您可以执行以下操作:

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